我想在本地linux上多进程进行socket通信,输出client和server侧示例代码
时间: 2023-03-28 12:02:40 浏览: 113
可以使用fork()函数创建多个进程,每个进程都可以通过socket进行通信。以下是一个简单的示例代码:
Server端示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT 8888
#define MAX_CONN 5
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";
// 创建socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, )) == ) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 设置socket选项
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);
// 绑定socket
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < ) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听socket
if (listen(server_fd, MAX_CONN) < ) {
perror("listen");
exit(EXIT_FAILURE);
}
// 接受连接请求
while (1) {
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < ) {
perror("accept");
exit(EXIT_FAILURE);
}
// 创建子进程处理连接
if (fork() == ) {
close(server_fd);
// 读取客户端发送的数据
valread = read(new_socket, buffer, 1024);
printf("%s\n", buffer);
// 发送数据给客户端
send(new_socket, hello, strlen(hello), );
printf("Hello message sent\n");
close(new_socket);
exit();
}
close(new_socket);
}
return ;
}
```
Client端示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT 8888
int main(int argc, char const *argv[]) {
int sock = , valread;
struct sockaddr_in serv_addr;
char *hello = "Hello from client";
char buffer[1024] = {};
// 创建socket
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);
// 将IP地址从点分十进制转换为二进制格式
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 ;
}
```
阅读全文