我是套接字编程的新手。 我的程序创建了两个写入服务器的客户端,该服务器使用线程读取数据,然后打印它们。我希望在发出请求时将所有这些数据发送给另一个客户端。我是否要创建另一个套接字,或者可以使用以前使用的套接字? 这是我的代码。 谢谢。
Server.c
#include<stdio.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
#include <arpa/inet.h>
#include <fcntl.h> // for open
#include <unistd.h> // for close
#include<pthread.h>
struct message { //dichiarazione struct
time_t timestamp;
char g; //process identifier
int x;
};
struct message client_message[10000];
int q=0;
static void * socketThread(void *arg)
{
int newSocket = *((int *)arg);
while(read(newSocket , &client_message[q] , sizeof(client_message))!=0) {
printf("message %d %d %ld\n",client_message[q].x,client_message[q].g,client_message[q].timestamp);
fflush(stdout);
sleep(1);
q++;
}
pthread_exit(NULL);
}
int main(){
int serverSocket, newSocket;
struct sockaddr_in serverAddr;
struct sockaddr_storage serverStorage;
socklen_t addr_size;
//Create the socket.
serverSocket = socket(AF_UNIX, SOCK_STREAM, 0);
// Configure settings of the server address struct
// Address family = Internet
serverAddr.sin_family = AF_UNIX;
//Set port number, using htons function to use proper byte order
serverAddr.sin_port = htons(55555);
//Set IP address to localhost
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
//INADDR_ANY;
//Set all bits of the padding field to 0
memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);
//Bind the address struct to the socket
bind(serverSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));
//Listen on the socket, with 40 max connection requests queued
if(listen(serverSocket,50)==0)
printf("Listening\n");
else
printf("Error\n");
pthread_t tid[2];
int i = 0;
while(i<2)
{
//Accept call creates a new socket for the incoming connection
addr_size = sizeof serverStorage;
newSocket = accept(serverSocket, (struct sockaddr *) &serverStorage, &addr_size);
//for each client request creates a thread and assign the client request to it to process
//so the main thread can entertain next request
if( pthread_create(&tid[i], NULL, socketThread, &newSocket) != 0 )
printf("Failed to create thread\n");
i++;
}
pthread_join(tid[1], NULL);
pthread_join(tid[0], NULL);
for(i=0;i<50;i++){
printf("%d aaa %d\n",client_message[i].x,client_message[i].g);
}
close(newSocket);
return 0;
}