给我写一个socket c语言应用程序,用于给多个客户端进程发送消息,实现一对多进程间通信,用sendmsg函数和struct sockaddr_un unet结构体实现进程间通信
时间: 2024-11-28 09:27:59 浏览: 27
用ASP.Net写一个发送ICQ信息的程序
在C语言中,要创建一个socket应用程序来实现实时一对多进程间的通信,你可以使用sendmsg函数和struct sockaddr_un结构体,这通常在Unix系统上进行网络无名套接字(Unix Domain Sockets)通信。以下是一个简单的示例,展示了如何初始化套接字、监听连接请求,并向所有连接的客户端发送消息:
```c
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <sys/un.h>
#include <sys/sendmsg.h>
#define MAX_CLIENTS 10
#define BUFFER_SIZE 1024
void *server_thread(void *arg) {
int server_sock = socket(AF_UNIX, SOCK_STREAM, 0);
struct sockaddr_un addr;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, "/tmp/server_socket");
if (bind(server_sock, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
perror("Failed to bind");
return NULL;
}
listen(server_sock, MAX_CLIENTS);
while (true) {
struct sockaddr_un client_addr;
socklen_t client_len = sizeof(client_addr);
int client_sock = accept(server_sock, (struct sockaddr *)&client_addr, &client_len);
char message[BUFFER_SIZE] = "Hello from server";
sendmsg(client_sock, (struct msghdr *) &message, strlen(message), 0, (struct iovec *)NULL, 1, MSG_NOSIGNAL); // Sending the message to each connected client
close(client_sock);
}
return NULL;
}
int main() {
pthread_t threads[MAX_CLIENTS];
for (size_t i = 0; i < MAX_CLIENTS; ++i) {
pthread_create(&threads[i], NULL, server_thread, NULL);
}
for (size_t i = 0; i < MAX_CLIENTS; ++i) {
pthread_join(threads[i], NULL);
}
return 0;
}
阅读全文