C++ 自定义消息包实现客户端与服务器通信

这里将消息头和消息内容用继承的方式写出来,发包的时候一定要注意字节对齐。

服务器

#define WIN32_LEAN_AND_MEAN
#define _WINSOCK_DEPRECATED_NO_WARNINGS

#include <windows.h>
#include <WinSock2.h>
#include <stdio.h>

#pragma comment(lib, "ws2_32.lib")

enum CMD {
	CMD_LOGIN,
	CMD_LOGIN_RESULT,
	CMD_LOGOUT,
	CMD_LOGOUT_RESULT,
	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;
};


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");

	// 接收客户端连接
	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");
	printf("新客户端加入:IP = %s\n", inet_ntoa(clientAddr.sin_addr));
	char _recvBuf[128] = {};
	while (true) {
		DataHeader header = {};
		int nLen = recv(_cSock, (char*)&header, sizeof(header), 0);
		if (nLen <= 0) {
			printf("客户端已退出,任务结束。");
			break;
		}
		
		// 处理请求
		switch (header.cmd) {
		case CMD_LOGIN:{
			Login login = {};
			recv(_cSock, (char*)&login+sizeof(DataHeader), sizeof(login)-sizeof(DataHeader), 0);
			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: {
			Logout logout = {};
			recv(_cSock, (char*)&logout+sizeof(DataHeader), sizeof(logout)-sizeof(DataHeader), 0);
			printf("收到命令: CMD_LOGIN 数据长度: %d userName=%s\n", \
				logout.dataLength, logout.userName);
			// 忽略判断用户密码是否正确的过程
			LoginResult ret;
			send(_cSock, (char*)&ret, sizeof(ret), 0);
		}
		default:
			header.cmd = CMD_ERROR;
			header.dataLength = 0;
			send(_cSock, (char*)&header, sizeof(header), 0);
		}
		
		
	}
	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_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;
};


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) {
		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;
}

 

点赞