前段时间学习了基于TCP协议下实现服务器与一个客户端的通信,服务器与多个客户端之间的通信,
以及客户端之间的互相通信。
下面就是我写的利用TCP和多线程技术实现客户端之间互相通信的代码:
服务器端:TcpServerb.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#define PORT 8888
struct info
{
int Tofd;
char buf[100];
};
void *MyReceive(void *arg)
{
struct info RecvBuf = {0};
int ret;
pthread_detach(pthread_self());
while (1)
{
ret = recv(*(int *)arg, &RecvBuf, sizeof(RecvBuf), 0); //接收消息,从fd里面接收
if (-1 == ret)
{
perror("recv");
exit(1);
}
if (!strcmp(RecvBuf.buf,"bye"))
{
//close(*(int *)arg);
break;
}
// printf("Recv From Client : %s\n", buf);
ret = send(RecvBuf.Tofd, &Rec