c++多线程实现的socket聊天室代码,可开多个客户端。

该程序修复了运行时的未定义行为问题,现在允许多个客户端连接。关键改动包括在CMakeLists.txt中链接ws2_32库。程序包含服务器和客户端部分,涉及TCP套接字通信,支持创建、加入聊天室及发送消息等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


2024-05-27 更新

  1. 在这个程序中有些未定义行为,导致有的编译器运行过程中出现create后服务器没有收到消息。如评论所说。现已修复。
  2. 打开多个客户端可以在你创建的项目中找到 .exe可执行程序,多次运行就可以打开多个客户端。
  3. 极简版删除
  4. 若是用clion编辑器,使用cmake构建项目,在CMakeLists.txt文件中添加link_libraries(ws2_32)如下:
cmake_minimum_required(VERSION 3.14)
project(项目名)

link_libraries(ws2_32)

set(CMAKE_CXX_STANDARD 标准)

add_executable(项目名 main.cpp
        1.cpp)


代码很乱,不建议仔细研究,需要讲解可留评论。
运行截图:
在这里插入图片描述
Server:

#include<iostream>
#include<winsock2.h>
#include<process.h>
#include<windows.h>
#include<vector>
#include<thread>
#include<set>
#pragma comment(lib,"ws2_32.lib")
#define PORT 65432    //定义要访问的服务器端口常量
#define MSG_SHOW 1
#define MSG_CREATE 2
#define MSG_JOIN 3
#define MSG_LEAVE 4
#define MSG_QUIT 5
#define MSG_EXIT 5
#define MSG_TALK 6
//#pragma comment(lib,"ws2_32.lib")
using namespace std;
int writefile(char* num, HANDLE fileHandle);
DWORD d1 = 0;

class MsgHead {
   
public:
    int msgType;
    int	dataLength;
};
class MsgShow :public MsgHead
{
   
public:
    MsgShow() {
   
        msgType = MSG_SHOW;
        dataLength = sizeof(MsgShow);
    }

};
class MsgCreate :public MsgHead
{
   
public:
    MsgCreate() {
   
        msgType = MSG_CREATE;
        dataLength = sizeof(MsgCreate);
    }

};
class MsgJoin :public MsgHead
{
   

public:
    int number;
    MsgJoin(int number) {
   
        msgType = MSG_JOIN;
        dataLength = sizeof(MsgJoin);
        this->number = number;
    }
};
class MsgLeave :public MsgHead
{
   
public:
    MsgLeave() {
   
        msgType = MSG_LEAVE;
        dataLength = sizeof(MsgLeave);
    }

};
class MsgExit :public MsgHead
{
   
public:
    MsgExit() {
   
        msgType = MSG_QUIT;
        dataLength = sizeof(MsgExit);
    }

};
class MsgTalk :public MsgHead
{
   
    char buff[1024];
public:
    MsgTalk() {
   
        memset(buff, '\0', sizeof(buff));
        msgType = MSG_TALK;
        dataLength = sizeof(MsgTalk);
    }
    char* getBuff() {
   
        return buff;
    }
};
vector<set<SOCKET>> vecMsgCreate;
void dealWithData(MsgHead* msg,SOCKET sClient) {
   

    if (msg->msgType == MSG_SHOW) {
   
        cout << "show" << endl;
        int identifier = 1;
        for (vector<set<SOCKET>>::iterator it = vecMsgCreate.begin();it != vecMsgCreate.end();it++)
        {
   
            cout << "**********chat room: " << identifier <<" ********" << endl;
            cout << " users: " << endl;
            for (set<SOCKET>::iterator j = it->begin();j != it->end(
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值