这几天一直在看TCP/IP这块的内容,写个简单socket通信demo,实现了多个客户端相互发送消息,以及服务端给多个客户端发送上线/下线消息
基本框架:
server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <pthread.h>
#define PORT 6666
#define NUM_MAX_WAIT 1
#define NUM_MAX_CHAT 2
typedef struct Message {
bool type; // 0: system 1: client
char buff[1024];
char name[30];
}Message;
typedef struct Client {
bool c_flage;
int c_fd;
}Client;
int sockfd = 0;
int num_chat = 0;
bool quit = false;
pthread_t ptid[2] = {};
Client client[4] = {};
void* pthread_comm(void* argc)
{
Client* cli_com = argc;
Message msg = {};
int ret = recv(cli_com->c_fd, &msg, sizeof(msg