我正在尝试编写一个服务器程序,该程序剥离3个线程并接受来自客户端的3个传入连接。
以下是当前代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <pthread.h>
void error(char *m)
{
perror(m);
}
void *createConnection(void *newsockfd){
int n;
void* buffer[256];
n = read(newsockfd,buffer,255);
if (n < 0) error("ERROR reading from socket");
printf("Message received:%s\n",buffer);
n = write(newsockfd,"I received your message",23);
if (n < 0)
error("ERROR writing back to socket");
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, port, clilen;
struct sockaddr_in serv_addr, cli_addr;
if (argc < 2)
error("ERROR, no port provided\n");
port = atoi(argv[1]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(port); //host to network
if (bind(sockfd, (struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR binding to socket");
listen(sockfd,2);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd,(struct sockaddr *)&cli_addr, &clilen);
pthread_t t1,t2,t3;
if( pthread_create( &t1 , NULL , createConnection , (void*) newsockfd) < 0)
{
perror("could not create thread 1");
return 1;
}
if( pthread_create( &t2 , NULL , createConnection , (void*) newsockfd) < 0)
{
perror("could not create thread 2");
return 1;
}
if( pthread_create( &t3 , NULL , createConnection , (void*) newsockfd) < 0)
{
perror("could not create thread 3");
return 1;
}
pthread_join( t1 , NULL);
pthread_join( t2 , NULL);
pthread_join( t3 , NULL);
return 0;
}
但是,一旦我运行它,它只接受来自一个客户端的请求。我不能理解这个问题。我们需要信号量吗?
最佳答案
问题是,生成三个线程来处理accept
返回的单个连接。
因为您想接受三个连接,所以将accept
调用移到每个线程中。
关于c - 剥离3个线程的服务器程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39474540/