基于tcp的网络聊天室c++利用的设计思路或方案的函数
时间: 2024-02-03 16:14:55 浏览: 153
lts.zip_TCP/IP聊天室
网络聊天室的设计思路主要包括以下几个方面:
1. 建立连接:使用socket函数建立客户端和服务器之间的TCP连接。
2. 发送消息:客户端向服务器发送消息时,使用send函数发送消息数据,服务器接收到消息时,使用recv函数接收消息数据。
3. 广播消息:服务器接收到一条客户端消息后,需要将该消息广播给其他客户端。可以采用链表或数组等数据结构存储所有客户端的socket描述符,然后遍历该结构体,使用send函数向所有客户端发送消息。
4. 处理并发:使用select函数实现多路复用,同时处理多个客户端的请求。
下面是一个简单的聊天室程序的C++代码示例:
```
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/select.h>
using namespace std;
#define SERVER_PORT 8888
#define MAX_CLIENT_NUM 10
#define MAX_MSG_SIZE 1024
int main()
{
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
perror("socket error");
exit(-1);
}
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("bind error");
exit(-1);
}
if (listen(server_socket, MAX_CLIENT_NUM) == -1) {
perror("listen error");
exit(-1);
}
int max_fd = server_socket;
fd_set read_set;
FD_ZERO(&read_set);
FD_SET(server_socket, &read_set);
int client_sockets[MAX_CLIENT_NUM];
int client_num = 0;
memset(client_sockets, -1, sizeof(client_sockets));
while (true) {
fd_set temp_set = read_set;
int ret = select(max_fd + 1, &temp_set, NULL, NULL, NULL);
if (ret == -1) {
perror("select error");
exit(-1);
}
if (FD_ISSET(server_socket, &temp_set)) {
struct sockaddr_in client_addr;
socklen_t client_addr_size = sizeof(client_addr);
int client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &client_addr_size);
if (client_socket == -1) {
perror("accept error");
continue;
}
if (client_num >= MAX_CLIENT_NUM) {
close(client_socket);
continue;
}
client_sockets[client_num] = client_socket;
client_num++;
FD_SET(client_socket, &read_set);
if (client_socket > max_fd) {
max_fd = client_socket;
}
char welcome_msg[MAX_MSG_SIZE];
sprintf(welcome_msg, "Welcome, your client ID is %d\n", client_num);
send(client_socket, welcome_msg, strlen(welcome_msg), 0);
}
for (int i = 0; i < client_num; i++) {
if (FD_ISSET(client_sockets[i], &temp_set)) {
char recv_msg[MAX_MSG_SIZE];
int ret = recv(client_sockets[i], recv_msg, MAX_MSG_SIZE, 0);
if (ret <= 0) {
close(client_sockets[i]);
FD_CLR(client_sockets[i], &read_set);
client_sockets[i] = -1;
client_num--;
}
else {
for (int j = 0; j < client_num; j++) {
if (client_sockets[j] != client_sockets[i] && client_sockets[j] != -1) {
send(client_sockets[j], recv_msg, ret, 0);
}
}
}
}
}
}
close(server_socket);
return 0;
}
```
阅读全文