服务器:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<unistd.h>
#include<ctype.h>
#include<arpa/inet.h>
#include<errno.h>
#include<time.h>
#define LISTENQ 1000 //最大连接数
#define MAXLINE 512 //发送消息的最长字节
#define MAXMEM 1000
#define NAMELEN 20 //名字长度
struct socketcfd
{
char name[20];
int fd;
};
int listenfd; //分别记录服务器端的套接字与连接的多个客户端的套接字
struct socketcfd connfd[MAXMEM];
void rcv_snd(void *arg) //服务器接受并转发消息函数
{
char* ask="请输入你的名字:";
char* ask1="使用说明:\n1、群聊可以直接发送消息,\n2、私聊请先输入@+人名+空格+内容,\n3、退出直接输入“bye”\n-------------------------------------------";
char* ch="此用户不存在";
char* ch1="群聊";
char* ch2="私聊";
char buff[MAXLINE]; //用户姓名
char buff1[MAXLINE]; //聊天内容(包括私聊和群聊,然后对它进行分析)
char buff2[MAXLINE]; //发送消息的时间
char buff3[MAXLINE]; //私聊时接受用户的姓名
char buff4[MAXLINE]; //私聊时发送的内容
time_t ticks;
int i=0;
int retval;
int len;
int k=0,j=0,m=0;
int p;
int n=(int *)arg;
//获取此进程对应的套接字用户的名字
write(connfd[n].fd,ask,strlen(ask));
len=read(connfd[n].fd,connfd[n].name,NAMELEN);
if(len>0){
connfd[n].name[len]=0;
}
printf("用户姓名:%s\n",connfd[n].nam