#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <pthread.h>
#define BUF_SIZE 1024
int listen_sock = 0;
char message[BUF_SIZE] = {0};
socklen_t clnt_addr_sz;
struct sockaddr_in serv_addr, clnt_addr;
int n = 0;
pthread_t tid;
int *pconnect_fd;
void *do_client(void *arg)
{
int connect_sock = *(int *)arg;
if (connect_sock < 0)
{
perror("Fail to accept");
exit(EXIT_FAILURE);
}
printf("==================================\n");
printf("connect_sock: %d\n",connect_sock);
printf("client IP: %s\n",inet_ntoa(clnt_addr.sin_addr));
printf("client port: %d\n",ntohs(clnt_addr.sin_port));
while(1)
{
memset(message,0,sizeof(message));
clnt_addr_sz=sizeof(clnt_addr);
n = recv(connect_sock, message, sizeof(message),0);
if (n<0)
{
perror("Fail to recv");
exit(EXIT_FAILURE);
}
else if(n == 0)
{
printf("client is not connect\n");
exit(EXIT_FAILURE);
}
printf("recv %d bytes: %s\n",n,message);
n = send(connect_sock, message, sizeof(message),0);
if (n<0)
{
perror("Fail to send");
exit(EXIT_FAILURE);
}
else if(n == 0)
{
printf("client is not connect");
exit(EXIT_FAILURE);
}
if (strncmp(message,"quit",4) == 0)
break;
}
free(arg);
}
void error_handling(char *message);
int main(int argc, char *argv[])
{
if(argc!=3)
{
printf("Usage: %s <port>\n", argv[0]);
exit(1);
}
listen_sock=socket(AF_INET, SOCK_STREAM, 0); //创建一个面向消息类型的套接字,注意第二个实参SOCK_DGRAM
if(listen_sock==-1)
error_handling("UDP socket creation error");
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr(argv[1]);
serv_addr.sin_port=htons(atoi(argv[2]));
clnt_addr_sz = sizeof(clnt_addr);
if (bind(listen_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr))==-1) //将通信地址信息绑定到套接字上,构成UDP套接字
error_handling("bind() error");
if ( listen(listen_sock,5) == -1)
{
perror("Fail to listen");
exit(EXIT_FAILURE);
}
printf("Listen...\n");
n = sizeof(serv_addr);
int ret = 0;
while(1)
{
pconnect_fd = (int *)malloc(sizeof(int));
*pconnect_fd = accept(listen_sock,(struct sockaddr*)&clnt_addr,&clnt_addr_sz);
ret = pthread_create(&tid,NULL,do_client,(void*)pconnect_fd);
if (ret != 0)
{
perror("Fail to pthread_create");
return -1;
}
pthread_detach(tid);
}
close(listen_sock);
return 0;
}
void error_handling(char *message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
tcp多线程源代码(自存)
最新推荐文章于 2024-10-08 11:43:40 发布