#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <pthread.h>
typedef struct sockinfo
{
int fd;
struct sockaddr_in addr;
pthread_t id;
} Sockinfo;
void* worker(void * arg);
//服务器端
void main(int * argc, const char* argv[])
{
//创建监听套接字
int lfd = socket(AF_INET,SOCK_STREAM,0);
//绑定监听套接字
struct sockaddr_in serv;
memset(&serv,0,sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = htonl(INADDR_ANY);
serv.sin_port = htons(6868);
bind(lfd,(struct sockaddr*)&serv, sizeof(serv));
//设置监听
listen(lfd, 36);
//等待并接收链接请求
struct sockaddr_in client;
socklen_t client_len = sizeof(client);
int i = 0;
Sockinfo info[256];
//for(i = 0; i<256; i++) info[i].fd = -1;//初始化fd为-1
while (1)
{
//接收链接并创建线程处理该链接
info[i].fd = accept(lfd,(struct sockaddr *)&info[i].addr, &client_len);
if(info[i].fd == -1) {
perror("accept error");
exit(1);
}
pthread_create(&info[i].id, NULL,worker, &info[i]);
pthread_detach(info[i].id);
i++;
if(i == 256)
{
break;
}
}
//关闭套接字
close(lfd);
pthread_exit(NULL);
}
void* worker(void * arg)
{
char buf[1024] = {0};
char ip[64];
Sockinfo *info = (Sockinfo *)arg;
printf(“client ip:%s client port:%d\n”,inet_ntop(AF_INET,&info->addr.sin_addr.s_addr,ip, sizeof(ip)),
ntohs(info->addr.sin_port));
//读数据
while (1) {
int len = read(info->fd,&buf,sizeof(buf));
if(-1 == len)
{
perror("read error\n");
exit(1);
}
else if(0 == len)
{
printf("client close connect\n");
break;
}
else{
printf("client send data:%s\n",buf);
//发送数据
write(info->fd,&buf,strlen(buf));
}
memset(buf,0,strlen(buf));
}
}