#include "socket.h"
int thread_count = 0;
pthread_t threads[MAX_THREAD_NUM];
/**
* 接收数据的执行函数
* @param conn_socket
*/
void recv_data(int conn_socket);
int Socket_Listent()
{
// 建立Socket
int server_socket = socket(PF_INET, SOCK_STREAM, 0);
if (server_socket < 0) {
printf(&quot;Socket create failed.\n&quot;);
return EXIT_FAILURE;
}
{
int opt = 1;
setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (opt));
}
// 设置服务器端监听套接字参数
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof (server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htons(INADDR_ANY);
server_addr.sin_port = htons(SERVER_PORT);
// 绑定端口
if (bind(server_socket, (struct sockaddr*) &server_addr, sizeof (server_addr)))
{
printf(&quot;Bind port %d failed.\n&quot;, SERVER_PORT);
return EXIT_FAILURE;
}
// 开始监听
if (listen(server_socket, LISTEN_QUEUE_LENGTH))
{
printf(&quot;Server Listen Failed!&quot;);
return EXIT_FAILURE;
}
// 开始处理客户端连接
bzero(&threads, sizeof(pthread_t) * MAX_THREAD_NUM);
while (1)
{
struct sockaddr_in client_addr;
socklen_t length = sizeof(client_addr);
// 建立客户端连接
int client_conn = accept(server_socket, (struct sockaddr*) &client_addr, &length);
if (client_conn < 0)
{
printf(&quot;Server Accept Failed!\n&quot;);
return EXIT_FAILURE;
}
// 新建线程, 使用新线程与客户端交互
int pthread_err = pthread_create(threads + (thread_count++), NULL, (void *)recv_data, (void *)client_conn);
if (pthread_err != 0)
{
printf(&quot;Create thread Failed!\n&quot;);
return EXIT_FAILURE;
}
}
close(server_socket);
return (EXIT_SUCCESS);
}
void recv_data(int conn_socket)
{
char buffer[BUFFER_SIZE];
bzero(buffer, BUFFER_SIZE);
int length = 0;
while (length = recv(conn_socket, buffer, BUFFER_SIZE, MSG_WAITALL))
{
if (length < 0)
{
printf(&quot;Server Recieve Data Failed! code %d\n&quot;, length);
}
printf(&quot;%s&quot;, buffer);
bzero(buffer, BUFFER_SIZE);
}
close(conn_socket);
}
int Client()
{
int cfd;
int recbytes;
int sin_size;
char buffer[1024]={0};
struct sockaddr_in s_add,c_add;
unsigned short portnum=SERVER_PORT;
printf(&quot;Hello,welcome to client !\r\n&quot;);
cfd = socket(AF_INET, SOCK_STREAM, 0);
if(-1 == cfd)
{
printf(&quot;socket fail ! \r\n&quot;);
return -1;
}
printf(&quot;socket ok !\r\n&quot;);
bzero(&s_add,sizeof(struct sockaddr_in));
s_add.sin_family=AF_INET;
s_add.sin_addr.s_addr= inet_addr(&quot;192.168.217.3&quot;);
s_add.sin_port=htons(portnum);
printf(&quot;s_addr = %#x ,port : %#x\r\n&quot;,s_add.sin_addr.s_addr,s_add.sin_port);
if(-1 == connect(cfd,(struct sockaddr *)(&s_add), sizeof(struct sockaddr)))
{
printf(&quot;connect fail !\r\n&quot;);
return -1;
}
printf(&quot;connect ok !\r\n&quot;);
if(-1 == (recbytes = read(cfd,buffer,1024)))
{
printf(&quot;read data fail !\r\n&quot;);
return -1;
}
printf(&quot;read ok\r\nREC:\r\n&quot;);
buffer[recbytes]='\0';
printf(&quot;%s\r\n&quot;,buffer);
getchar();
close(cfd);
return 0;
} |