1.完成局域网CS模型,局域网内一个服务器,多个客户端连接一个服务器,完成局域网聊天。
#include <myhead.h>
#define SERIP "192.168.0.137"
#define SERPORT 8888
#define BACKLOG 50
int main(int argc,const char *argv[])
{
//1创建套接字
int oldfd = socket(AF_INET,SOCK_STREAM,0);
if(oldfd == -1)
{
perror("socket");
return -1;
}
//2启动端口号快速复用
int kkk = 9;
if(setsockopt(oldfd,SOL_SOCKET,SO_REUSEADDR, &kkk, sizeof(kkk)) == -1)
{
perror("setsockopt");
return -1;
}
printf("端口号快速复用成功\n");
struct sockaddr_in address = {
.sin_family = AF_INET,
.sin_port = htons(SERPORT),
.sin_addr.s_addr = inet_addr(SERIP)
};
//3绑定IP和端口号
if (bind(oldfd,(struct sockaddr *)&address,sizeof(address)) == -1)
{
perror("bind");
return -1;
}
//4监听
if (listen(oldfd,BACKLOG) == -1)
{
perror("listen");
return -1;
}
printf("监听成功\n");
char buff[1024] = {0};
fd_set readfds;
int max = BACKLOG;
int maxfd;
int newfd;
int client_sockets[BACKLOG];
struct sockaddr_in client_addresses[BACKLOG];
int i;
for (i = 0; i < max; i++)
{
client_sockets[i] = 0;
}
while (1)
{
FD_ZERO(&readfds);
FD_SET(oldfd, &readfds);
maxfd = oldfd;
for(i = 0;i < max;i++)
{
int sd = client_sockets[i];
if(sd > 0)
{
FD_SET(sd, &readfds);
}
if(sd > maxfd)
{
maxfd = sd;
}
}
int res = select(maxfd + 1,&readfds,NULL,NULL,NULL);
if(res == -1)
{
perror("select");
return -1;
}
if(res == 0)
{
printf("timeout");
return -1;
}
int addrlen = sizeof(address);
if(FD_ISSET(oldfd,&readfds))
{
if((newfd = accept(oldfd,(struct sockaddr *)&address,(socklen_t *)&addrlen)) == -1)
{
perror("accept");
return -1;
}
printf("客户端%s:%d已上线\n",inet_ntoa(address.sin_addr),ntohs(address.sin_port));
for (i = 0; i < max; i++)
{
if (client_sockets[i] == 0)
{
client_sockets[i] = newfd;
client_addresses[i] = address;
break;
}
}
}
for (i = 0; i < max; i++)
{
bzero(buff,sizeof(buff));
int sd = client_sockets[i];
if(FD_ISSET(sd, &readfds))
{
int len = recv(sd,buff,sizeof(buff),0);
if(len == 0)
{
printf("客户端下线\n");
close(sd);
client_sockets[i] = 0;
}
else
{
char aim_ip[16];
char message[1024];
int m = 0;
while (buff[m] != 32 && buff[m] != '\0')
{
aim_ip[m] = buff[m];
m++;
}
aim_ip[m] = '\0'; // 添加字符串结束符
m++; // 跳过分隔符 ':'
int n = 0;
while (buff[m] != '\0') {
message[n] = buff[m];
m++;
n++;
}
message[n] = '\0'; // 添加字符串结束符
//send(sd,buff,sizeof(buff),0);//回复客户端消息
int j;
for (j = 0;j < max;j++)
{
if (client_sockets[j] > 0&&strcmp(inet_ntoa(client_addresses[j].sin_addr),aim_ip) == 0)
{
char success[] = "SUCCESS";
send(sd,success,sizeof(success),0);//回复客户端消息
send(client_sockets[j], message, strlen(message), 0);
break;
}
}
if (j == max)
{
char chazhao[] = "The client with the desired IP could not be found";
send(sd,chazhao,sizeof(chazhao),0);//回复客户端消息
printf("找不到目标 IP 的客户端\n");
}
}
}
}
}
return 0;
}