我想创建一个多客户端处理服务器。它有1个线程来处理所有客户端,但scanf函数不工作,而while循环继续运行。
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <pthread.h>
#define PORT 80
int totalclient = 0;
int clientsocket[100];
void error_message(char *m)
{
printf("%s", m);
exit(1);
}
void *multi_clients()
{
int c1;
while(1)
printf("Server is running, enter your option for clients\n");
scanf(" %d", &c1); // here scanf is not working.
pthread_exit(NULL);
}
int main(void)
{
pthread_t Thread;
int sock, valread, valthread;
struct sockaddr_in saddr;
int addrlen = sizeof(saddr);
int opt = 1;
char buffer[] = "hello";
int temp=0;
if((sock = socket(AF_INET, SOCK_STREAM, 0)) == 0)
error_message("socket cannot be created\n");
if((setsockopt(sock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt))))
error_message("setsocket");
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = INADDR_ANY;
saddr.sin_port = htons(PORT);
if(bind(sock, (struct sockaddr *)&saddr, addrlen) <0)
error_message("bind failed\n");
if(listen(sock, 3) < 0)
error_message("listen");
if((valthread = pthread_create(&Thread, NULL, multi_clients,
NULL)))
error_message("thread\n");
printf("accepting connection....\n");
while(1)
{
if((clientsocket[totalclient] = accept(sock,
(struct sockaddr *)&saddr, (socklen_t*)&addrlen)) <0)
printf("error accepting connection\n");
else
send(clientsocket[totalclient], buffer, strlen(buffer), 0);
totalclient++;
}
return 0;
}
是他们在多线程中从用户那里获取输入的任何其他更好的选择。