服务器使用select函数,客户端使用多线程
服务器
#define WIN32_LEAN_AND_MEAN
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include
#include
#include
#include
#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 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("客户端已退出,任务结束。",_cSock);
return -1;
}
// 处理请求
switch (header->cmd) {
case CMD_LOGIN: {
recv(_cSock, szRecv + sizeof(DataHeader), header->dataLength - sizeof(DataHeader), 0);
Login* login = (Login*)szRecv;
printf("收到客户端请求: CMD_LOGIN 数据长度: %d userName=%s Passwd=%s\n", \
_cSock,login->dataLength, login->userName, login->PassWord);
// 忽略判断用户密码是否正确的过程
LoginResult ret;
send(_cSock, (char*)&ret, sizeof(LoginResult), 0);
}
break;
case CMD_LOGOUT: {
recv(_cSock, szRecv + sizeof(DataHeader), header->dataLength - sizeof(DataHeader), 0);
Logout* logout = (Logout*)szRecv;
printf("收到客户端请求: CMD_LOGOUT 数据长度: %d userName=%s\n", \
_cSock,logout->dataLength, logout->userName);
// 忽略判断用户密码是否正确的过程
LoginResult ret;
send(_cSock, (char*)&ret, sizeof(ret), 0);
}
break;
default:
DataHeader header = { 0, CMD_ERROR };
send(_cSock, (char*)&header, sizeof(header), 0);
}
return 0;
}
int main()
{
// 启动Windows socket 2.x环境
WORD ver = MAKEWORD(2, 2);
WSADATA dat;
WSAStartup(ver, &dat);
//----------------
// --用Socket API建立简易TCP服务器
// 创建一个socket
SOCKET _sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
// 绑定用于接受客户端连接的网络端口
sockaddr_in _sin = {};
_sin.sin_family = AF_INET;
_sin.sin_port = htons(9527);
_sin.sin_addr.S_un.S_addr = INADDR_ANY;
if (SOCKET_ERROR == bind(_sock, (sockaddr*)&_sin, sizeof(_sin)))
printf("ERROR,绑定用于接受客户端连接的网络端口失败...\n");
else
printf("绑定端口成功...\n");
// 监听端口
if (SOCKET_ERROR == listen(_sock, 5))
printf("监听网络端口失败...\n");
else
printf("监听网络端口成功...\n");
//char _recvBuf[128] = {};
while (true) {
// 伯克利 socket 描述符
fd_set fdRead;
fd_set fdWrite;
fd_set fdExp;
FD_ZERO(&fdRead);
FD_ZERO(&fdWrite);
FD_ZERO(&fdExp);
FD_SET(_sock, &fdRead);
FD_SET(_sock, &fdWrite);
FD_SET(_sock, &fdExp);
for (int n = (int)g_clients.size()-1; n >=0; n--)
FD_SET(g_clients[n], &fdRead);
timeval t = { 1,0 }; // 时间参数,非阻塞模式
int ret = select(_sock + 1, &fdRead, &fdWrite, &fdExp, &t);
if (ret < 0) {
printf("select任务结束\n");
break;
}
if (FD_ISSET(_sock, &fdRead)) {
FD_CLR(_sock, &fdRead);
// 接受客户端连接
sockaddr_in clientAddr = {};
int nAddrLen = sizeof(sockaddr_in);
SOCKET _cSock = INVALID_SOCKET;
_cSock = accept(_sock, (sockaddr*)&clientAddr, &nAddrLen);
if (INVALID_SOCKET == _cSock)
printf("接受到无效客户端SOCKET...\n");
// 像其他客户端发送通知
for (int n = (int)g_clients.size() - 1; n >= 0; n--) {
NewUserJoin userJoin;
send(g_clients[n], (const char*)&userJoin,
sizeof(NewUserJoin), 0);
}
g_clients.push_back(_cSock);
printf("新客户端<%d>加入:IP = %s\n",_cSock, inet_ntoa(clientAddr.sin_addr));
}
for (size_t n = 0; n < fdRead.fd_count;n++) {
if (-1 == processor(fdRead.fd_array[n])) {
auto iter = find(g_clients.begin(), g_clients.end(), fdRead.fd_array[n]);
if (iter != g_clients.end())
g_clients.erase(iter);
}
}
//printf("空闲时间处理其他业务..\n");
}
for (size_t n = g_clients.size() - 1; n >= 0; n--) {
closesocket(g_clients[n]);
}
closesocket(_sock);
WSACleanup();
return 0;
}
客户端
#define WIN32_LEAN_AND_MEAN
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include
#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;
};
int processor(SOCKET _cSock)
{
// 缓冲区
char szRecv[4096] = {};
int nLen = recv(_cSock, (char*)&szRecv, sizeof(DataHeader), 0);
DataHeader* header = (DataHeader*)szRecv;
if (nLen <= 0) {
printf("与服务器断开连接,任务结束。\n");
return -1;
}
// 处理请求
switch (header->cmd) {
case CMD_LOGIN_RESULT: {
recv(_cSock, szRecv + sizeof(DataHeader), header->dataLength - sizeof(DataHeader), 0);
LoginResult* login = (LoginResult*)szRecv;
printf("收到服务端%d消息:CMD_LOGIN_RESULT,数据长度:%d\n",
_cSock, header->dataLength);
}
break;
case CMD_LOGOUT_RESULT: {
recv(_cSock, szRecv + sizeof(DataHeader), header->dataLength - sizeof(DataHeader), 0);
LogOutResult* logout = (LogOutResult*)szRecv;
printf("收到服务端%d消息:CMD_LOGOUT_RESULT,数据长度:%d\n",
_cSock, header->dataLength);
}
break;
case CMD_NEW_USER_JOIN: {
recv(_cSock, szRecv + sizeof(DataHeader), header->dataLength - sizeof(DataHeader), 0);
NewUserJoin* userJoin = (NewUserJoin*)szRecv;
printf("收到服务端%d消息:CMD_NEW_USER_JOIN,数据长度:%d\n",
_cSock, header->dataLength);
}
break;
}
return 0;
}
bool g_bRun = true;
void cmdThread(SOCKET _sock)
{
while (true) {
char cmdBuf[256] = {};
scanf("%s", cmdBuf);
if (0 == strcmp(cmdBuf, "exit")) {
g_bRun = false;
printf("退出\n");
return;
}
else if (0 == strcmp(cmdBuf, "login")) {
Login login;
strcpy(login.userName, "lyd");
strcpy(login.PassWord, "lyd");
send(_sock, (const char*)&login, sizeof(Login), 0);
}
else if (0 == strcmp(cmdBuf, "logout")) {
Login logout;
strcpy(logout.userName, "lyd");
strcpy(logout.PassWord, "lyd");
send(_sock, (const char*)&logout, sizeof(Logout), 0);
}
}
}
int main()
{
// 启动Windows socket 2.x环境
WORD ver = MAKEWORD(2, 2);
WSADATA dat;
WSAStartup(ver, &dat);
//----------------
// 建立一个socket
SOCKET _sock = socket(AF_INET, SOCK_STREAM, 0);
if (INVALID_SOCKET == _sock)
printf("创建套接字错误...\n");
// 连接服务器 connect
sockaddr_in _sin = {};
_sin.sin_family = AF_INET;
_sin.sin_port = htons(9527);
_sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
int ret = connect(_sock, (sockaddr*)&_sin, sizeof(sockaddr_in));
if (SOCKET_ERROR == ret)
printf("连接服务器错误...\n");
else
printf("连接Socket成功...\n");
// 启动线程函数
std::thread t1(cmdThread,_sock);
t1.detach(); // 与主线程分离
while (g_bRun) {
fd_set fdReads;
FD_ZERO(&fdReads);
FD_SET(_sock, &fdReads);
timeval t = { 1,0 };
int ret = select(_sock, &fdReads, 0, 0, &t);
if (ret < 0) {
printf("select任务结束\n");
break;
}
if (FD_ISSET(_sock, &fdReads)) {
FD_CLR(_sock, &fdReads);
if (-1 == processor(_sock)) {
printf("select任务结束2\n");
break;
}
}
}
// 关闭套接字
closesocket(_sock);
WSACleanup();
return 0;
}