帮我写多人聊天室C++
时间: 2023-02-12 22:44:42 浏览: 140
基于c++语言的socket多人聊天室源码.zip
5星 · 资源好评率100%
很高兴为您写多人聊天室的 C 代码。在这里,我将向您展示一个简单的实现方式。
首先,需要使用多线程来实现多人聊天。可以使用 pthread 库来实现线程。
其次,需要使用 socket 来实现网络通信。
下面是一个简单的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 8888
#define MAX_CLIENTS 10
#define BUFFER_SIZE 1024
int client_socket[MAX_CLIENTS];
pthread_t client_thread[MAX_CLIENTS];
void *handle_client(void *arg) {
int client_index = *((int *)arg);
char buffer[BUFFER_SIZE];
int bytes_received;
while (1) {
bytes_received = recv(client_socket[client_index], buffer, BUFFER_SIZE, 0);
if (bytes_received <= 0) {
break;
}
for (int i = 0; i < MAX_CLIENTS; i++) {
if (i != client_index && client_socket[i] != 0) {
send(client_socket[i], buffer, bytes_received, 0);
}
}
}
printf("Client %d disconnected\n", client_index);
close(client_socket[client_index]);
client_socket[client_index] = 0;
return NULL;
}
int main(int argc, char *argv[]) {
int server_socket;
struct sockaddr_in server_address;
int opt = 1;
int addrlen = sizeof(server_address);
for (int i = 0; i < MAX_CLIENTS; i++) {
client_socket[i] = 0;
}
if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
if (setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INAD
阅读全文