1. 源码
server.cpp
#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <string>
#include <thread>
#include <vector>
#pragma comment (lib, "Ws2_32.lib")
#define IP_ADDRESS "192.168.56.1"
#define DEFAULT_PORT "3504"
#define DEFAULT_BUFLEN 512
struct client_type {
int id;
SOCKET socket;
};
const char OPTION_VALUE = 1;
const int MAX_CLIENTS = 5;
//Function Prototypes
int process_client(client_type& new_client, std::vector<client_type>& client_array, std::thread& thread);
int main();
int process_client(client_type& new_client, std::vector<client_type>& client_array, std::thread& thread) {
std::string msg = "";
char tempmsg[DEFAULT_BUFLEN] = "";
//Session
while (1) {
memset(tempmsg, 0, DEFAULT_BUFLEN);
if (new_client.socket != 0) {
int iResult = recv(new_client.socket, tempmsg, DEFAULT_BUFLEN, 0);
if (iResult != SOCKET_ERROR) {
if (strcmp("", tempmsg))
msg = "Client #" + std::to_string(new_client.id) + ": " + tempmsg;
std::cout << msg.c_str(

这是一个使用C++和Winsock库编写的多线程TCP服务器示例,能够接受多个客户端连接并广播消息。代码中定义了一个结构体`client_type`来存储客户端的ID和套接字,并通过`process_client`函数处理每个客户端的通信。服务器在接收到新的客户端连接时,会创建一个新的线程来处理该连接,同时限制了最大客户端数量为5。当客户端断开连接时,会通知其他客户端。
最低0.47元/天 解锁文章





