请问:在socket编程的服务器端,想采用多线程来处理客户端的命令,应该怎样写啊?
比如当客户端发来了请求,服务端就响应(可不可以生成一个线程来接收客户端的要求啊,),这样主线程就可以空下来,继续
为下一个客户端的要求生成线程.
------解决方案--------------------网上这种例子很多google下....
------解决方案--------------------新建一个线程,阻塞于select或者recvfrom,接收到消息后处理,或者给主线程一个消息,让主线程处理.
------解决方案-------------------- if ( ( listenfd = socket ( AF_INET, SOCK_STREAM, 0 ) ) <0 ) {
exit(1);
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
bzero ( & ( server.sin_zero ) , 8);
server.sin_port = htons ( socklist[count].serverport ) ;
if((rval = bind ( listenfd, (struct sockaddr *)&server, sizeof(server) ) ) < 0 ) {
exit(1);
}
rval = listen ( listenfd, 10 );
if ( rval != 0 ) {
close(listenfd);
return;
}
/***********************************************************************
* Will accept the connection request comes from client.
**********************************************************************/
for(;;){
strulen = sizeof(tcpaddr);
if ( ( connfd = accept ( listenfd, (struct sockaddr *)&tcpaddr, &strulen ) ) < 0 ) {
continue;
}
/*******************************************
* Fork a child process
* to deal with client request.
******************************************/
if ( fork() == 0 ) {
char tmpbuf[2048], decbuf[2048], encbuf[2048], recvbuf[2048], sendbuf[2048];
int recvlen, sendlen, declen, enclen, tmpbuflen;
close(listenfd);
//线程处理自己信息
}