客户端
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<stdlib.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<pthread.h>
struct sockaddr_in remote;
char buf[1024];
int ad[10];
void *thread_fun(void *arg)
{
while(1)
{
ssize_t _s=read(ad[(int)arg],buf,sizeof(buf)-1);
if(_s>0)
{
buf[_s]=0;
printf("client# %s\n",buf);
}
else
{
printf("client is quit!\n");
break;
}
}
return NULL;
}
int startup(int _port,const char* _ip)
{
int sock=socket(AF_INET,SOCK_STREAM,0);//打开一个网络通信窗口
if(sock<0)
{
perror("socket");
exit(1);
}
struct sockaddr_in local;
local.sin_family=AF_INET;
local.sin_port=htons(_port);
local.sin_addr.s_addr=inet_addr(_ip);
socklen_t len=sizeof(local);
if(bind(sock,(struct sockaddr*)&local,len)<0)//绑定一个固定的网络地址和端口号
{
perror("bind");
exit(2);
}
if(listen(sock,5)<0)//导致套接口从closed状态换到listen状态
{
perror("listen");
exit(3);
}
return sock;
}
int main(int argc,char* argv[])
{
if(argc!=3)
{
printf("Usage: [local_ip] [local_port]",argv[0]);
return 3;
}
int listen_socket=startup(atoi(argv[2]),argv[1]);
pthread_t tid[10];
int err;
int i=0;
socklen_t len=sizeof(struct sockaddr_in);
while(1)
{
ad[i]=accept(listen_socket,(struct sockaddr*)&remote,&len);
if(ad[i]<0)
{
perror("accept");
continue;
}
printf("client,ip:%s,port:%d\n",inet_ntoa(remote.sin_addr)\
,ntohs(remote.sin_port));
err=pthread_create(&tid[i],NULL,thread_fun,(void *)i);
if(err !=0)
{
printf("create new thread failed\n");
close(ad[i]);
}
i++;
}
close(listen_socket);
return 0;
}