代码
通过创建一个线程,使服务器的读写分离,主线程用于读客户端发送的数据,其他线程用来向客户端写数据,互不影响。
#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <arpa/inet.h>
#define PORT 6666
//读
void Read(int client_socket)
{
char buf[1024] = {"aaa"};
while (1)
{
int ret = read(client_socket,buf,sizeof(buf)-1);
if (-1 == ret)
{
perror ("read error");
}
if (0 == ret)
{
printf ("客户端退出\n");
break;
}
buf[ret] = '\0';
printf ("收到客户端数据:%s\n", buf);
}
}
//写
void *Write(void *v)
{
int client_socket = *(int *)v;
char buf[1024];
while(1)
{
fgets(buf,1024,stdin);
ssize_t fd = write(client_socket,buf,strlen(buf));
if(0 == fd)
{
perror("写入失败");
break;
}
}
}
// 监听套接字
int init()
{
int listen_socket = socket(AF_INET, SOCK_STREAM, 0);
if(-1 == listen_socket)
{
perror("创建套接字失败");
return -1;
}
s