⑴ C语言基础网络编程求助 如何实现多线程
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
void*thread(void*);
int client[5],i;
main()
{
int serverSocket= socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in server_addr;
struct sockaddr_in clientAddr;
int addr_len = sizeof(clientAddr);
//线程
pthread_t id;
pthread_attr_t attr;
pthread_attr_init(&attr);////////////////////////////////////////////////
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
//创建地址
bzero(&server_addr,sizeof(server_addr));
server_addr.sin_family =AF_INET;
server_addr.sin_port = htons(5555);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
//绑定
bind(serverSocket,(struct sockaddr *)&server_addr,sizeof(server_addr));
listen(serverSocket,5);
for(i=0;i<5;i++)
{
client[i] = accept(serverSocket,(struct sockaddr *)&clientAddr,(socklen_t*)&addr_len);
pthread_create(&id,&attr,thread,(void *)&client[i]);/////////////////////////////////
pthread_join(id,NULL);
}
close(serverSocket);/////////////////////////
return 0;
}
void* thread(void* argv)
{
char buffer[200];
int a=i;
int s_c = *((int*)argv);///////////////////
while(1)
{
int n = recv(s_c,buffer,sizeof(buffer),0);
if(n > 0)
printf("客户端发过来的 : %s\n",buffer);
else
return;
}
close(s_c);
}