服务器使用select函数,客户端使用多线程
服务器
#define WIN32_LEAN_AND_MEAN
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <windows.h>
#include <WinSock2.h>
#include <stdio.h>
#include <vector>
#pragma comment(lib, "ws2_32.lib")
enum CMD {
CMD_LOGIN,
CMD_LOGIN_RESULT,
CMD_LOGOUT,
CMD_LOGOUT_RESULT,
CMD_NEW_USER_JOIN,
CMD_ERROR,
};
// 消息头
struct DataHeader {
short dataLength;
short cmd;
};
struct Login:public DataHeader {
Login() {
dataLength = sizeof(Login);
cmd = CMD_LOGIN;
}
char userName[32];
char PassWord[32];
};
struct LoginResult: public DataHeader {
LoginResult() {
dataLength = sizeof(LoginResult);
cmd = CMD_LOGIN_RESULT;
result = 0;
}
int result;
};
struct Logout:public DataHeader {
Logout() {
dataLength = sizeof(Logout);
cmd = CMD_LOGOUT;
}
char userName[32];
};
struct LogOutResult:public DataHeader {
LogOutResult() {
dataLength = sizeof(LogOutResult);
cmd = CMD_LOGOUT_RESULT;
result = 0;
}
int result;
};
struct NewUserJoin :public DataHeader
{
NewUserJoin() {
dataLength = sizeof(NewUserJoin);
cmd = CMD_NEW_USER_JOIN;
sock = 0;
}
int sock;
};
std::vector<SOCKET> g_clients;
int processor(SOCKET _cSock)
{
// 缓冲区
char szRecv[4096] = {};
int nLen = recv(_cSock, (char*)&szRecv, sizeof(DataHeader), 0);
DataHeader* header = (DataHeader*)szRecv;
if (nLen <= 0) {
printf("客户端<Socket=%d>已退出,任务结束。",_cSock);
return -1;
}
// 处理请求
switch (header->cmd) {
case CMD_LOGIN: {
recv(_cSock, szRecv + sizeof(DataHeader), header->dataLength - sizeof(DataHeader), 0);
Login* login = (Login*)szRecv;
printf("收到客户端<Socket=%d>请求: CMD_LOGIN 数据长度: %d userName=%s Passwd=%