2024-05-27 更新
- 在这个程序中有些未定义行为,导致有的编译器运行过程中出现create后服务器没有收到消息。如评论所说。现已修复。
- 打开多个客户端可以在你创建的项目中找到 .exe可执行程序,多次运行就可以打开多个客户端。
- 极简版删除
- 若是用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(