模拟聊天室程序//带注释求修改,没人帮吗?
//服务器程序#include <stdio.h>#include <sys/socket.h>#include <stdlib.h>#include <netinet/in.h>#include <arpa/inet.h>#include <string.h>#include <pthread.h>#include <time.h>#include <semaphore.h>int fds[100];//保存所有的客户端的socket描述符,最大100int size=0;void sendtoall(const char* msg)//向所有人发送信息函数{ int i; for(i=0; i<size; i++) { send(fds[i], msg, strlen(msg), 0); }}void* task(void* p)//子进程函数{ int sd = *(int*)p; char buf[100] = {}; while(1) { sem_wait(&lock);//加锁有问题行吗??????? memset(buf, 0, sizeof(buf)); recv(sd, buf, sizeof(buf), 0); sendtoall(buf);//发送给所有在fds数组内的客户端 sem_post(&lock); }} int main(){ sem_t lock; sem_init(&lock,0,1);//初始化锁变量 int sockfd = socket(PF_INET, SOCK_STREAM, 0);//获取sockfd, if(sockfd==-1)perror("创建socket失败"),exit(-1); struct sockaddr_in addr;//建立网络信息 addr.sin_family = PF_INET; addr.sin_port = htons(8888); addr.sin_addr.s_addr = inet_addr("192.168.180.53"); int res = bind(sockfd, (struct sockaddr*)&addr, sizeof(addr));//绑定 if(res==-1)perror("绑定失败"),exit(-1); printf("绑定成功\n"); listen(sockfd, 10);//监听 struct sockaddr_in fromaddr={}; socklen_t len; int sd,sd_temp;//每次while(1)循环,sd的值,会不断改变,故保存在sd_temp变量中 while(1) { sd = accept(sockfd, (struct sockaddr*)&fromaddr,&len);//与客户端建立联系 if(sd==-1) { perror("等待客户端连接失败"); continue; } fds[size++] = sd;//客户端socket ++ pthread_t tid;//建立子进程 sd_temp = sd; pthread_create(&tid, 0, task, &ssd); } sem_destroy(&lock);}[code=C/C++]//客户端代码#include <stdio.h>#include <sys/socket.h>#include <stdlib.h>#include <netinet/in.h>#include <arpa/inet.h>#include <string.h>#include <pthread.h>void* task(void* p)//子进程函数{ int sd = *(int*)p; char buf[100] = {}; while(1)//如何改写代码,自己输入的消息,不会被收到????? { memset(buf, 0, sizeof(buf)); recv(sd, buf, sizeof(buf), 0); printf("%s\n", buf); }}int main(){ int sockfd = socket(PF_INET, SOCK_STREAM, 0);//创建socket if(sockfd==-1)perror("创建socket失败"),exit(-1); struct sockaddr_in addr;//建立通信地址 addr.sin_family = PF_INET; addr.sin_port = htons(8888); addr.sin_addr.s_addr = inet_addr("192.168.180.53"); int res = connect(sockfd, (struct sockaddr*)&addr, sizeof(addr));//连接服务器 if(res==-1)perror("连接失败"),exit(-1); printf("连接成功\n"); pthread_t tid;//建立子进程 pthread_create(&tid, 0, task, &sockfd); printf("请输入你的姓名:");//本机参与聊天代码 char name[20] = {}; scanf("%s", name); while(1)///客户端代码,用while循环,服务器程序会退出,客服端死循环?????? { scanf("%*c"); char buf[100] = {}; printf("输入内容:"); scanf("%s", buf); char msg[120] = {}; strcpy(msg, name); strcat(msg, ":"); strcat(msg, buf); send(sockfd, msg, strlen(msg), 0);//发送信息 }}
记录下发送消息那个客户端socket描述符,
然后发送的时候判断下接受客户端socket描述符是否等于记录下来的socket描述符,如果是则不发送。
修改下你的代码:
void sendtoall(const char* msg, int fd)//向所有人发送信息函数
{
int i;
for(i=0; i<size; i++)
{
if(fd != fds[i])
{
send(fds[i], msg, strlen(msg), 0);
}
}
}
void* task(void* p)//子进程函数
{
int sd = *(int*)p;
char buf[100] = {};
while(1)
{
sem_wait(&lock);//加锁有问题行吗???????
memset(buf, 0, sizeof(buf));
recv(sd, buf, sizeof(buf), 0);
sendtoall(buf, sd);//发送给所有在fds数组内的客户端
sem_post(&lock);
}
}