UDP聊天室
客户端
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<unistd.h>
#include<pthread.h>
#include<stdlib.h>
#include"08_linklist.h"
#include<net/if.h>
//打印错误信息的宏函数
#define ERR_MSG(msg) do{\
fprintf(stderr, "__%d__", __LINE__);\
perror(msg);\
}while(0)
#define IP "192.168.8.125"
#define POST "8888"
int sfd;
void *MSG_rcv(void *arg) //接收服务器信息
{
struct usrmsg cin; //创建消息结构体
while(1)
{
bzero(cin.message, sizeof(cin.message)); //数据包信息部分清空
socklen_t addrlen = sizeof(cin.sin);
if(recvfrom(sfd, cin.message, sizeof(cin.message), 0, (struct sockaddr*)&(cin.sin), &addrlen) < 0)
{
ERR_MSG("recvfrom");
return NULL;
}
if(cin.message[0] == 'Q') //被服务器踢下线
{
exit(0);
}else if(cin.message[0] == 'C') //正常会话
{
fprintf(stderr,">>>%s:%s\n", cin.message+1, cin.message+11);
fprintf(stderr,">>>");
}else if(cin.message[0] == 'F') //服务器消息
{
fprintf(stderr," 系统消息:%s\n", cin.message+11);
fprintf(stderr,">>>");
}
}
}
int main(int argc, const char *argv[])
{
//创建报式套接字
sfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sfd < 0)
{
ERR_MSG("socket");
return -1;
}
printf("create socket success\n");
//填充服务器的IP地址以及端口号
struct usrmsg usr;
usr.sin.sin_family = AF_INET;
usr.sin.sin_port = htons(atoi(POST));
usr.sin.sin_addr.s_addr = inet_addr(IP);
bzero(usr.message, sizeof(usr.message