服务器程序
#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 = 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_LOGIN_RESULT;
result = 0;
}
int result;
};
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("收到命令: CMD_LOGIN 数据长度: %d userName=%s Passwd=%s\n", \
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_LOGIN 数据长度: %d userName=%s\n", \
logout->dataLength, logout->userName);
// 忽略判断用户密码是否正确的过程
LoginResult ret;
send(_cSock, (char*)&ret, sizeof(ret), 0);
}
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("新客户端加入:IP = %s\n", 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 <windows.h>
#include <WinSock2.h>
#include <iostream>
#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 = 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_LOGIN_RESULT;
result = 0;
}
int result;
};
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");
char cmdBuf[128] = {};
while (true) {
/*fd_set fdReads;
FD_ZERO(&fdReads);
FD_SET(_sock, &fdReads);
int ret = select(_sock, &fdReads, 0, 0, 0);
if (ret < 0) {
printf("select任务结束\n");
break;
}
if (FD_ISSET(_sock, &fdReads)) {
FD_CLR(_sock, &fdReads);
}*/
std::cin >> cmdBuf;
if (0 == strcmp(cmdBuf, "exit"))
break;
else if (0 == strcmp(cmdBuf, "login")) {
Login login;
strcpy(login.userName, "lyd");
strcpy(login.PassWord, "lydmima");
// 向服务器发送请求命令
send(_sock, (const char *)&login, sizeof(login), 0);
// 接受服务器返回的数据
LoginResult loginRet = {};
recv(_sock, (char*)&loginRet, sizeof(loginRet), 0);
printf("LoginResult %d\n", loginRet.result);
}
else if (0 == strcmp(cmdBuf, "logout")) {
Logout logout;
strcpy(logout.userName, "lyd");
// 5 向服务器发送请求命令
send(_sock, (const char *)&logout, sizeof(logout), 0);
// 接受服务器返回的数据
LogOutResult logoutRet = {};
recv(_sock, (char*)&logoutRet, sizeof(logoutRet), 0);
printf("LogoutResult: %d \n", logoutRet.result);
}
else
printf("不支持命令,请重新输入。\n");
}
// 关闭套接字
closesocket(_sock);
WSACleanup();
return 0;
}