int listenSock,acceptSock;
int n;
struct sockaddr_in servAddr;
/*********创建套接字*********/
if((listenSock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("create sock error\n");
exit(0);
}
memset( &servAddr, 0 , sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(6006); //端口号
n=1;
/*********绑定套接字**********/
setsockopt(listenSock,SOL_SOCKET,SO_REUSEADDR,&n,sizeof(int));
if(bind(listenSock,(struct sockaddr *)&servAddr,sizeof(servAddr)) < 0) {
printf("bind failed\n");
}
/********开启侦听最多10个客户端*********/
if(listen(listenSock, 10 ) < 0) {
printf("listen failed\n");
}
while(1)
{
acceptSock = accept(listenSock,NULL,NULL); //等待客户端连接
if(acceptSock < 0)
continue;
if((n=fork())==0)
{
char buffer[1024];
close(listenSock);
n=read(acceptSock,buffer,1024); //等待读取客户端发送的信息
write(acceptSock,"hello",5); //发送信息给指定客户端
printf("buffer=%s\n",buffer);
close(acceptSock); //关闭此连接
exit(0);
}
else if(n<0)
printf("Fork Error\n");
close(acceptSock);
}
阅读(249) | 评论(0) | 转发(0) |