我想在本地linux上多进程进行socket通信,输出client和server侧示例代码
时间: 2023-03-28 14:02:41 浏览: 107
可以使用fork()函数创建多个进程,每个进程都可以进行socket通信。以下是client和server侧示例代码:
Server侧代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 808
int main() {
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {};
char *hello = "Hello from server";
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, )) == ) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// Forcefully attaching socket to the port 808
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// Forcefully attaching socket to the port 808
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < ) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < ) {
perror("listen");
exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < ) {
perror("accept");
exit(EXIT_FAILURE);
}
valread = read(new_socket, buffer, 1024);
printf("%s\n", buffer);
send(new_socket, hello, strlen(hello), );
printf("Hello message sent\n");
return ;
}
```
Client侧代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 808
int main(int argc, char const *argv[]) {
int sock = , valread;
struct sockaddr_in serv_addr;
char *hello = "Hello from client";
char buffer[1024] = {};
if ((sock = socket(AF_INET, SOCK_STREAM, )) < ) {
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if(inet_pton(AF_INET, "127...1", &serv_addr.sin_addr)<=) {
printf("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < ) {
printf("\nConnection Failed \n");
return -1;
}
send(sock, hello, strlen(hello), );
printf("Hello message sent\n");
valread = read(sock, buffer, 1024);
printf("%s\n", buffer);
return ;
}
```
阅读全文