用c++写一个聊天室服务端
时间: 2023-06-17 21:08:58 浏览: 101
一个C++写的聊天室
好的,下面是一个简单的聊天室服务端的C++代码:
```cpp
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#include <vector>
using namespace std;
const int MAX_CLIENTS = 10;
vector<int> clients(MAX_CLIENTS, 0);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *handle_client(void *arg) {
int client_sock = *(int *)arg;
char buffer[1024];
int read_size;
while ((read_size = read(client_sock, buffer, 1024)) > 0) {
buffer[read_size] = '\0';
pthread_mutex_lock(&mutex);
for (int i = 0; i < MAX_CLIENTS; ++i) {
if (clients[i] != 0 && clients[i] != client_sock) {
write(clients[i], buffer, strlen(buffer));
}
}
pthread_mutex_unlock(&mutex);
}
pthread_mutex_lock(&mutex);
for (int i = 0; i < MAX_CLIENTS; ++i) {
if (clients[i] == client_sock) {
clients[i] = 0;
break;
}
}
pthread_mutex_unlock(&mutex);
close(client_sock);
pthread_exit(NULL);
}
int main(int argc, char *argv[]) {
int server_sock, client_sock, c, *new_sock;
struct sockaddr_in server, client;
server_sock = socket(AF_INET, SOCK_STREAM, 0);
if (server_sock == -1) {
cerr << "Could not create socket" << endl;
return EXIT_FAILURE;
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(8888);
if (bind(server_sock, (struct sockaddr *)&server, sizeof(server)) < 0) {
cerr << "Bind failed" << endl;
return EXIT_FAILURE;
}
listen(server_sock, 3);
cout << "Waiting for incoming connections..." << endl;
c = sizeof(struct sockaddr_in);
while (true) {
client_sock = accept(server_sock, (struct sockaddr *)&client, (socklen_t *)&c);
if (client_sock == -1) {
cerr << "Accept failed" << endl;
continue;
}
pthread_mutex_lock(&mutex);
for (int i = 0; i < MAX_CLIENTS; ++i) {
if (clients[i] == 0) {
clients[i] = client_sock;
break;
}
}
pthread_mutex_unlock(&mutex);
pthread_t thread_id;
new_sock = new int;
*new_sock = client_sock;
if (pthread_create(&thread_id, NULL, handle_client, (void *)new_sock) < 0) {
cerr << "Could not create thread" << endl;
return EXIT_FAILURE;
}
}
close(server_sock);
return EXIT_SUCCESS;
}
```
这个聊天室服务端使用了多线程来同时处理多个客户端的连接和消息发送。当一个新的客户端连接进来时,服务端会将其加入到客户端列表中,然后启动一个新的线程来处理该客户端的消息。当该客户端的socket关闭时,服务端会将其从客户端列表中删除。
客户端列表使用了一个vector来存储,因此,如果需要支持更多的客户端连接,只需要调整MAX_CLIENTS常量的值即可。
此外,为了保证多线程下的线程安全,使用了pthread_mutex_t来实现互斥锁。每当客户端连接或退出时,都需要使用互斥锁进行加锁和解锁。
阅读全文