实现功能:
客户端
1.开启时输入昵称并往服务器端发送带有客户端昵称
2.开启后能随时往服务器端发送聊天内容
3.收到服务器发来的数据时判别是否为自己发送的数据,若不是则输出num编号所指引的内容
4. 当输入quit时退出
服务器
1.接受各个客户端的信息,新用户则将其存入链表中并向各个用户发送有新用户加入的信息
2.当用户输入quit时,删除该用户信息并向各个用户发送该用户退出的信息
3.当收到正常聊天信息时发送给各个用户
代码
客户端
客户端中ip设定为本机的ip地址,通过外部传参传入不同的端口号用以区分不同用户
#include <sys/types.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#define ERR_MSG(msg) do {\
fprintf(stderr,"_%d_",__LINE__);\
perror(msg);\
}while(0)
#define IP "192.168.31.242"
//#define PORT 8888 // 1024~49151
typedef struct MSG{
int num;
char name[20];
char data[256];
}MSG;
int sfd;
struct sockaddr_in cin;
socklen_t addrlen= sizeof(cin);
MSG msg;
char cname[20];
void *shou(void*arg)
{
while(1)
{
if(recv(sfd, &msg, sizeof(msg),0) < 0)
{
ERR_MSG("recvfrom");
return NULL;
}
if (strcmp(msg.name,cname)!=0) //判断是否为自己发送的
{
if(msg.num==3)
{
printf("%s:%s\n",msg.name,msg.data);
}
if (msg.num==4)
{
printf("%s进入聊天室\n",msg.name);
}
}
}
pthread_exit(NULL);
}
void *fa(void*arg)
{