/** I/O复用 一个客户端一个线程
*
* gcc -o 50_06th_server_threads 50_06th_server_threads.c -lpthread
*/
#include
#include
#include
#include
#include
#include
#include
#include /* See NOTES */
#include
#include
void *task_client(void *arg) {
int clientfd = *(int *)arg;
char buf[1024];
printf(“this is a new thread you got connected %d\n“ clientfd);
pthread_detach(pthread_self()); //标记为DETACHED状态,完成后释放自己占用的资源。
while (1) {
if (recv(clientfd buf sizeof(buf)-1 0) > 0) { //MSG_OOB
} else {
perror(“recv“);
break;
}
printf(“Received a message : %s\n“ buf);
}
printf(“this is over \n“);
}
int main(int argc char *argv[]) {
struct sockaddr_in addr;
int nb_connection = 5;
int listenfd = socket(AF_INET SOCK_STREAM 0);
if (listenfd == -1) {
return -1;
}
int on = 1; //允许重复使用本地地址与套接字进行绑定
setsockopt(listenfd SOL_SOCKET SO_REUSEADDR (char *) &on sizeof(int));
addr.sin_family = AF_INET;
addr.sin_port = htons(5050);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
//addr.sin_addr.s_
评论
共有 条评论