#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/select.h>
const int Port = 8888;
pthread_mutex_t g_mutext;
struct pthread_data{
struct sockaddr_in client_addr;
int sock_fd;
};
void *serveForClient(void * arg);
int main(void){
int sock_fd;
struct sockaddr_in mysock;
struct pthread_data pdata;
pthread_t pt;
socklen_t sin_size = sizeof(struct sockaddr_in);
struct sockaddr_in client_addr;
int new_fd;
//初始化socket
sock_fd = socket(AF_INET,SOCK_STREAM,0);
//编辑地址信息
memset(&mysock, 0, sizeof(mysock));
mysock.sin_family = AF_INET;
mysock.sin_port = htons(Port);
mysock.sin_addr.s_addr = INADDR_ANY;
//绑定地址,然后监听
bind(sock_fd,(struct sockaddr *)&mysock,sizeof(struct sockaddr));
if(listen(sock_fd,10) < -1){
printf("listen error.\n");
}
printf("listening...\n");
while(1){
//accpet
new_fd = accept(sock_fd, (struct sockaddr *)&client_addr, &sin_size);
pdata.client_addr = client_addr;
pdata.sock_fd = new_fd;
pthread_create(&pt, NULL, serveForClient, (void *)&pdata);
}
//close(new_fd);
close(sock_fd);
return 0;
}
void *serveForClient(void *arg){
struct pthread_data *pdata = (struct pthread_data*)arg;
int new_fd = pdata->sock_fd;
char recvbuf[1024];
fd_set fs_read;
int fs_sel;
struct timeval time;
int i = 0;
while(i < 3){
FD_ZERO(&fs_read);
FD_SET(new_fd, &fs_read);
time.tv_sec = 5;
time.tv_usec = 0;
fs_sel = select(new_fd + 1, &fs_read, NULL, NULL, &time);
if ( fs_sel ){
memset(recvbuf,0,sizeof(recvbuf));
if(read(new_fd, recvbuf, sizeof(recvbuf))>0)
printf("recv:%s\n", recvbuf);
}
else{
i++;
}
}
close(new_fd);
pthread_exit(0);
}
gcc -o tcp_server tcp_server.c -lpthread