概述
目录
主要实现了两个任务:
一,将客户端和服务器端移植到其他ubuntu和macos系统中,实现跨平台的网络通讯
二,将客户端和服务器端进行封装,并进行跨平台测试
主要实现了两个任务:
- 将客户端和服务器端移植到其他ubuntu和macos系统中,实现跨平台的网络通讯
- 将客户端和服务器端进行封装,并进行跨平台测试
一,将客户端和服务器端移植到其他ubuntu和macos系统中,实现跨平台的网络通讯
需要注意,移动的到linux下时,select函数的第一个参数需要加1,(最近会写一篇关于select函数的博客)
运行截图:
下图时windows和ubuntu分别做服务器端的运行截图:
服务器端代码:
#define WIN32_LEAN_AND_MEAN
#include<iostream>
#ifdef _WIN32
#include<windows.h>
#include<Winsock2.h>
#else
#include<unistd.h>
#include<arpa/inet.h>
#include<string.h>
#define SOCKET int
#define INVALID_SOCKET (SOCKET)(~0)
#define SOCKET_ERROR (-1)
#endif
#include<vector>
#include<thread>
using namespace std;
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;
};
vector<SOCKET> g_clients;
int processor(SOCKET _cSock)
{
cout<<"受到";
//缓冲区
char szRecv[4096] = {};
//5,接受客户端的请求数据
int nLen = (int)recv(_cSock, (char*)&szRecv, sizeof(DataHeader), 0);
DataHeader *header = (DataHeader*)szRecv;
if (nLen <= 0)
{
cout << "客户端已经退出,任务结束" << endl;
return -1;
}
switch (header->cmd)
{
case CMD_LOGIN:
{
//做数据偏移
recv(_cSock, szRecv + sizeof(DataHeader), header->dataLength - sizeof(DataHeader), 0);
Login *login = (Login*)szRecv;
cout << "收到命令:CMD_LOGIN, 数据长度:" << login->dataLength;
cout << " UserName:" << login->userName << " PassWord:" << login->PassWord << endl;
//忽略判断用户名密码是否正确的过程
LoginResult ret;
send(_cSock, (const char*)&ret, sizeof(LoginResult), 0);
}
break;
case CMD_LOGOUT:
{
recv(_cSock, szRecv + sizeof(DataHeader), header->dataLength - sizeof(DataHeader), 0);
Login *logout = (Login*)szRecv;
cout << "收到命令:CMD_LOGIN, 数据长度:" << logout->dataLength;
cout << " UserName:" << logout->userName << endl;
//忽略判断用户名密码是否正确的过程
LogoutResult ret;
send(_cSock, (const char*)&ret, sizeof(Logout), 0);
}
break;
default:
{
DataHeader header = { 0, CMD_ERROR };
send(_cSock, (const char*)&header, sizeof(DataHeader), 0);
}
break;
}
return 0;
}
int main()
{
#ifdef _WIN32
//启动Windows socket 2.x环境
WORD ver = MAKEWORD(2, 2);
WSADATA dat;
WSAStartup(ver, &dat);
#endif
//---------------------------------
//1,建立一个socket
SOCKET _sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
//2,bind 绑定用于接受客户端连接的网络接口
sockaddr_in _sin = {};
_sin.sin_family = AF_INET;
_sin.sin_port = htons(4567);
#ifdef _WIN32
_sin.sin_addr.S_un.S_addr = INADDR_ANY;
#else
_sin.sin_addr.s_addr = INADDR_ANY;
#endif
if (SOCKET_ERROR == bind(_sock, (sockaddr*)&_sin, sizeof(_sin)))
{
cout << "错误,绑定网络端口失败" << endl;
}
else
{
cout << "绑定网络端口成功" << endl;
}
//3,listen 监听网络端口
if (SOCKET_ERROR == listen(_sock, 5))
{
cout << "错误,监听网络端口失败" << endl;
}
else
{
cout << "监听网络端口成功" << endl;
}
while (true)
{
//伯克利套接字
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);
SOCKET maxSock = _sock;
for (int n = (int)g_clients.size() - 1; n >= 0; n--)
{
FD_SET(g_clients[n],&fdRead);
if(maxSock < g_clients[n])
{
maxSock = g_clients[n];
}
}
//nfds 是一个整数值,是指fd_set集合中所有描述符(socket)的范围,而不是数量
//即是所有文件描述符最大值+1,在Windows中这个参数可以写0
//添加非阻塞
timeval t = { 1, 0 };
int ret = select(maxSock + 1, &fdRead, &fdWrite, &fdExp, &t);
if (ret < 0)
{
cout << "select任务结束" << endl;
break;
}
if (FD_ISSET(_sock, &fdRead))
{
FD_CLR(_sock, &fdRead);
//4,accept 等待客户端连接
sockaddr_in clientAddr = { };
int nAddrlen = sizeof(clientAddr);
SOCKET _cSock = INVALID_SOCKET;
#ifdef _WIN32
_cSock = accept(_sock, (sockaddr *)&clientAddr, &nAddrlen);
#else
_cSock = accept(_sock, (sockaddr *)&clientAddr, (socklen_t *)&nAddrlen);
#endif
if (INVALID_SOCKET == _cSock)
{
cout << "错误,接受到无效的客户端连接" << endl;
}
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);
cout << "新的客户端加入:"<<(int)_cSock<<" "<< inet_ntoa(clientAddr.sin_addr) << endl;
}
for (int n = (int)g_clients.size() - 1; n >= 0; n--)
{
if (FD_ISSET(g_clients[n], &fdRead))
{
if (processor(g_clients[n]) == -1)
{
auto iter = g_clients.begin();
if (iter != g_clients.end())
{
g_clients.erase(iter);
}
}
}
}
//cout << "空闲时间处理其他业务" << endl;
}
for (int n = g_clients.size() - 1; n >= 0; n--)
{
#ifdef _WIN32
closesocket(g_clients[n]);
#else
close(g_clients[n]);
#endif
}
#ifdef _WIN32
//7,关闭套接字closesocket
closesocket(_sock);
//清除Windows socket环境
WSACleanup();
#else
close(_sock);
#endif
system("pause");
return 0;
}
客户端代码:
#define WIN32_LEAN_AND_MEAN
#ifdef _WIN32
#include<windows.h>
#include<Winsock2.h>
#else
#include<unistd.h>
#include<arpa/inet.h>
#include<string.h>
#define SOCKET int
#define INVALID_SOCKET (SOCKET)(~0)
#define SOCKET_ERROR (-1)
#endif
#pragma comment(lib,"ws2_32.lib")
#include<iostream>
#include<thread>
using namespace std;
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[1024] = {};
//5,接受客户端的请求数据
int nLen = recv(_cSock, (char*)&szRecv, sizeof(DataHeader), 0);
DataHeader *header = (DataHeader*)szRecv;
if (nLen <= 0)
{
cout << "与服务器断开连接,任务结束" << endl;
return -1;
}
switch (header->cmd)
{
case CMD_LOGIN_RESULT:
{
recv(_cSock, szRecv + sizeof(DataHeader), header->dataLength - sizeof(DataHeader), 0);
LoginResult *login = (LoginResult*)szRecv;
cout << "收到服务端消息:CMD_LOGIN_RESULT " << _cSock << " 数据长度:" << login->dataLength << endl;
}
break;
case CMD_LOGOUT_RESULT:
{
recv(_cSock, szRecv + sizeof(DataHeader), header->dataLength - sizeof(DataHeader), 0);
LogoutResult *logout = (LogoutResult*)szRecv;
cout << "收到服务端消息:CMD_LOGOUT_RESULT "<< " 数据长度:" << logout->dataLength << endl;
}
break;
case CMD_NEW_USER_JOIN:
{
recv(_cSock, szRecv + sizeof(DataHeader), header->dataLength - sizeof(DataHeader), 0);
NewUserJoin *userJoin = (NewUserJoin*)szRecv;
cout << "收到服务端消息:CMD_NEW_USER_JOIN "<< " 数据长度:" << userJoin->dataLength << endl;
}
break;
}
return 0;
}
bool g_bRun = true;
void cmdThread(SOCKET sock)
{
while (1)
{
char cmdBuf[256] = {};
cin >> cmdBuf;
if (strcmp(cmdBuf, "exit") == 0)
{
g_bRun = false;
cout << "退出子线程" << endl;
return;
}
else if (strcmp(cmdBuf, "login") == 0)
{
//线程thread;
Login login;
strcpy(login.userName, "lyd");
strcpy(login.PassWord, "lydmima");
//5,向服务器发送请求
send(sock, (const char *)&login, sizeof(Login), 0);
}
else if (strcmp(cmdBuf, "logout") == 0)
{
//线程thread;
Logout logout;
strcpy(logout.userName, "lyd");
//5,向服务器发送请求
send(sock, (const char *)&logout, sizeof(Logout), 0);
}
else{
cout << "不支持的命令" << endl;
}
}
}
int main()
{
#ifdef _WIN32
//启动Windows socket 2.x环境
WORD ver = MAKEWORD(2, 2);
WSADATA dat;
WSAStartup(ver, &dat);
#endif
//---------------------------------
//1,用Socket API建立建立TCP客户端
SOCKET _sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(_sock == INVALID_SOCKET)
{
cout<<"建立socket失败"<<endl;
}
else
{
cout<<"建立socket成功"<<endl;
}
//2,连接服务器 connect
sockaddr_in _sin = {};
_sin.sin_family = AF_INET;
_sin.sin_port = htons(4567);
#ifdef _WIN32
_sin.sin_addr.S_un.S_addr = inet_addr("***.***.***.*");
#else
_sin.sin_addr.s_addr = inet_addr("***.***.***.*");
#endif
int ret = connect(_sock, (struct sockaddr*)&_sin, sizeof(sockaddr_in));
if (SOCKET_ERROR == ret)
{
cout << "错误,连接Socket失败" << endl;
}
else
{
cout << "连接Socket成功" << endl;
}
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+1, &fdReads, 0, 0, NULL);
if (ret < 0)
{
cout << "select 任务结束1" << endl;
break;
}
if (FD_ISSET(_sock, &fdReads))
{
FD_CLR(_sock, &fdReads);
if (-1 == processor(_sock))
{
cout << "select 任务结束2" << endl;
break;
}
}
}
#ifdef _WIN32
//7,关闭套接字closesocket
closesocket(_sock);
//清除Windows socket环境
WSACleanup();
#else
close(_sock);
#endif
cout << "已退出" << endl;
return 0;
}
二,将客户端和服务器端进行封装,并进行跨平台测试
服务器端代码:
- EasyTcpServer.hpp
#ifndef _EasyTcpServer_hpp_
#define _EasyTcpServer_hpp_
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include<windows.h>
#include<Winsock2.h>
#pragma comment(lib,"ws2_32.lib")
#else
#include<unistd.h>
#include<arpa/inet.h>
#include<string.h>
#define SOCKET int
#define INVALID_SOCKET (SOCKET)(~0)
#define SOCKET_ERROR (-1)
#endif
#include<iostream>
#include"MessageHeader.hpp"
#include<vector>
using namespace std;
class EasyTcpServer
{
private:
SOCKET _sock;
vector<SOCKET> g_clients;
public:
EasyTcpServer()
{
_sock = INVALID_SOCKET;
}
virtual ~EasyTcpServer()
{
Close();
}
//初始化Socket
SOCKET InitSocket()
{
#ifdef _WIN32
//启动Windows socket 2.x环境
WORD ver = MAKEWORD(2, 2);
WSADATA dat;
WSAStartup(ver, &dat);
#endif
//1,用Socket API建立建立TCP客户端
if (_sock != INVALID_SOCKET)
{
cout << "_sock=" << (int)_sock << "关闭旧连接" << endl;
Close();
}
_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (_sock == INVALID_SOCKET)
{
cout << "建立socket失败" << endl;
}
else
{
cout << (int)_sock << " 建立socket成功" << endl;
}
return _sock;
}
//绑定IP和端口号
int Bind(const char *ip, unsigned short port)
{
//if (_sock != INVALID_SOCKET)
//{
// InitSocket();
//}
//2,bind 绑定用于接受客户端连接的网络接口
sockaddr_in _sin = {};
_sin.sin_family = AF_INET;
_sin.sin_port = htons(port);
#ifdef _WIN32
if (ip){
_sin.sin_addr.S_un.S_addr = inet_addr(ip);
}
else{
_sin.sin_addr.S_un.S_addr = INADDR_ANY;
}
#else
if (ip){
_sin.sin_addr.s_addr = inet_addr(ip);
}
else{
_sin.sin_addr.s_addr = INADDR_ANY;
}
#endif
int ret = ::bind(_sock, (sockaddr*)&_sin, sizeof(_sin));
if (SOCKET_ERROR == ret)
{
cout << (int)_sock << "错误,绑定网络端口失败" << endl;
}
else
{
cout << "绑定网络端口成功" << port << endl;
}
return ret;
}
//监听端口号
int Listen(int n)
{
int ret = listen(_sock, n);
if (SOCKET_ERROR == ret)
{
cout << (int)_sock << " 错误,监听网络端口失败" << endl;
}
else
{
cout << (int)_sock << " 监听网络端口成功" << endl;
}
return ret;
}
//接受客户端连接
SOCKET Accept()
{
//4,accept 等待客户端连接
sockaddr_in clientAddr = {};
int nAddrlen = sizeof(clientAddr);
SOCKET _cSock = INVALID_SOCKET;
#ifdef _WIN32
_cSock = accept(_sock, (sockaddr *)&clientAddr, &nAddrlen);
#else
_cSock = accept(_sock, (sockaddr *)&clientAddr, (socklen_t *)&nAddrlen);
#endif
if (INVALID_SOCKET == _cSock)
{
cout << (int)_sock << " 错误,接受到无效的客户端连接" << endl;
}
else
{
NewUserJoin userJoin;
SendDataToAll(&userJoin);
g_clients.push_back(_cSock);
cout << "新的客户端加入:" << (int)_cSock << " ";
cout << inet_ntoa(clientAddr.sin_addr) << endl;
}
return _sock;
}
//关闭Socket
void Close()
{
if (_sock != INVALID_SOCKET)
{
#ifdef _WIN32
for (int n = (int)g_clients.size() - 1; n >= 0; n--)
{
closesocket(g_clients[n]);
}
//8,关闭套接字closesocket
closesocket(_sock);
//清除Windows socket环境
WSACleanup();
#else
for (int n = (int)g_clients.size() - 1; n >= 0; n--)
{
close(g_clients[n]);
}
//8,关闭套接字closesocket
close(_sock);
#endif
}
}
//处理网络消息
bool OnRun()
{
if (isRun())
{
//伯克利套接字
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);
SOCKET maxSock = _sock;
for (int n = (int)g_clients.size() - 1; n >= 0; n--)
{
FD_SET(g_clients[n], &fdRead);
if (maxSock < g_clients[n])
{
maxSock = g_clients[n];
}
}
//nfds 是一个整数值,是指fd_set集合中所有描述符(socket)的范围,而不是数量
//即是所有文件描述符最大值+1,在Windows中这个参数可以写0
//添加非阻塞
timeval t = { 1, 0 };
int ret = select(maxSock + 1, &fdRead, &fdWrite, &fdExp, &t);
if (ret < 0)
{
cout << "select任务结束" << endl;
Close();
return false;
}
if (FD_ISSET(_sock, &fdRead))
{
FD_CLR(_sock, &fdRead);
Accept();
}
for (int n = (int)g_clients.size() - 1; n >= 0; n--)
{
if (FD_ISSET(g_clients[n], &fdRead))
{
if (RecvData(g_clients[n]) == -1)
{
auto iter = g_clients.begin();
if (iter != g_clients.end())
{
g_clients.erase(iter);
}
}
}
}
return true;
}
return false;
}
//是否工作中
bool isRun()
{
return _sock != INVALID_SOCKET;
}
//接收数据 处理粘包哦拆分包
int RecvData(SOCKET _cSock)
{
//缓冲区
char szRecv[1024] = {};
//5,接受客户端的请求数据
int nLen = (int)recv(_cSock, (char*)&szRecv, sizeof(DataHeader), 0);
DataHeader *header = (DataHeader*)szRecv;
if (nLen <= 0)
{
cout << "客户端已经退出,任务结束" << endl;
return -1;
}
recv(_cSock, szRecv + sizeof(DataHeader), header->dataLength - sizeof(DataHeader), 0);
OnNetMsg(_cSock, header);
return 0;
}
//响应网络消息
virtual void OnNetMsg(SOCKET _cSock, DataHeader *header)
{
switch (header->cmd)
{
case CMD_LOGIN:
{
//做数据偏移
Login *login = (Login*)header;
cout << "收到命令:CMD_LOGIN, 数据长度:" << login->dataLength;
cout << " UserName:" << login->userName << " PassWord:" << login->PassWord << endl;
//忽略判断用户名密码是否正确的过程
LoginResult ret;
//send(_cSock, (const char*)&ret, sizeof(LoginResult), 0);
SendData(_cSock, (DataHeader *)&ret);
}
break;
case CMD_LOGOUT:
{
Login *logout = (Login*)header;
cout << "收到命令:CMD_LOGIN, 数据长度:" << logout->dataLength;
cout << " UserName:" << logout->userName << endl;
//忽略判断用户名密码是否正确的过程
LogoutResult ret;
//send(_cSock, (const char*)&ret, sizeof(Logout), 0);
SendData(_cSock, (DataHeader *)&ret);
}
break;
default:
{
DataHeader header = { 0, CMD_ERROR };
//send(_cSock, (const char*)&header, sizeof(DataHeader), 0);
SendData(_cSock, &header);
}
break;
}
}
//发送指定Socket数据
int SendData(SOCKET _cSock, DataHeader *header)
{
if (isRun() && header)
{
return (int)send(_cSock, (const char *)header, header->dataLength, 0);
}
return SOCKET_ERROR;
}
//群发消息
void SendDataToAll(DataHeader *header)
{
for (int n = (int)g_clients.size() - 1; n >= 0; n--)
{
SendData(g_clients[n], header);
}
}
};
#endif
- MessageHeader.hpp
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;
};
- server.cpp
#include"EasyTcpServer.hpp"
int main()
{
EasyTcpServer server;
server.InitSocket();
server.Bind(nullptr, 4567);
server.Listen(5);
while (server.isRun())
{
server.OnRun();
//cout<<空闲处理其他业务<<endl;
}
server.Close();
cout << "已退出" << endl;
system("pause");
return 0;
}
客户端代码:
- EasyTcpClient.hpp
#ifndef _EasyTcpClient_hpp_
#define _EasyTcpClient_hpp_
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include<windows.h>
#include<Winsock2.h>
#pragma comment(lib,"ws2_32.lib")
#else
#include<unistd.h>
#include<arpa/inet.h>
#include<string.h>
#define SOCKET int
#define INVALID_SOCKET (SOCKET)(~0)
#define SOCKET_ERROR (-1)
#endif
#include<iostream>
#include "MessageHeader.hpp"
using namespace std;
class EasyTcpClient
{
SOCKET _sock;
public:
EasyTcpClient()
{
_sock == INVALID_SOCKET;
}
virtual ~EasyTcpClient()
{
Close();
}
//初始化socket
void InitSocket()
{
#ifdef _WIN32
//启动Windows socket 2.x环境
WORD ver = MAKEWORD(2, 2);
WSADATA dat;
WSAStartup(ver, &dat);
#endif
//1,用Socket API建立建立TCP客户端
if (_sock == INVALID_SOCKET)
{
cout << "_sock=" << _sock << "关闭旧连接" << endl;
Close();
}
_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (_sock == INVALID_SOCKET)
{
cout << "建立socket失败" << endl;
}
else
{
cout << "建立socket成功" << endl;
}
}
//连接服务器
int Connect(char *ip, unsigned short port)
{
if (_sock != INVALID_SOCKET)
{
InitSocket();
}
//2,连接服务器 connect
sockaddr_in _sin = {};
_sin.sin_family = AF_INET;
_sin.sin_port = htons(4567);
#ifdef _WIN32
_sin.sin_addr.S_un.S_addr = inet_addr(ip);
#else
_sin.sin_addr.s_addr = inet_addr(ip);
#endif
int ret = connect(_sock, (sockaddr*)&_sin, sizeof(sockaddr_in));
if (SOCKET_ERROR == ret)
{
cout << "错误,连接Socket失败" << endl;
}
else
{
cout << "连接Socket成功" << endl;
}
return 0;
}
//7,关闭套接字closesocket
void Close()
{
if (_sock != INVALID_SOCKET)
{
#ifdef _WIN32
closesocket(_sock);
//清除Windows socket环境
WSACleanup();
#else
close(_sock);
#endif
}
}
//处理网络消息
bool OnRun()
{
if (isRun())
{
fd_set fdReads;
FD_ZERO(&fdReads);
FD_SET(_sock, &fdReads);
//添加非阻塞
//timeval t = { 1, 0 };
int ret = select(_sock + 1, &fdReads, 0, 0, NULL);
if (ret < 0)
{
cout << "_sock=" << _sock << " 任务结束1" << endl;
return false;
}
if (FD_ISSET(_sock, &fdReads))
{
FD_CLR(_sock, &fdReads);
if (-1 == RecvData(_sock))
{
cout << "_sock=" << _sock << " 任务结束2" << endl;
return false;
}
}
return true;
}
return false;
}
//是否工作中
bool isRun()
{
return _sock != INVALID_SOCKET;
}
//接收数据 处理粘包,拆分包
int RecvData(SOCKET _cSock)
{
//缓冲区
char szRecv[1024] = {};
//5,接受客户端的请求数据
int nLen = (int)recv(_cSock, (char*)&szRecv, sizeof(DataHeader), 0);
DataHeader *header = (DataHeader*)szRecv;
if (nLen <= 0)
{
cout << "与服务器断开连接,任务结束" << endl;
return -1;
}
recv(_cSock, szRecv + sizeof(DataHeader), header->dataLength - sizeof(DataHeader), 0);
OnNetMsg(header);
return 0;
}
//响应网络消息
virtual void OnNetMsg(DataHeader *header)
{
switch (header->cmd)
{
case CMD_LOGIN_RESULT:
{
LoginResult *login = (LoginResult*)header;
cout << "收到服务端消息:CMD_LOGIN_RESULT,数据长度:" << login->dataLength << endl;
}
break;
case CMD_LOGOUT_RESULT:
{
LogoutResult *logout = (LogoutResult*)header;
cout << "收到服务端消息:CMD_LOGOUT_RESULT,数据长度:" << logout->dataLength << endl;
}
break;
case CMD_NEW_USER_JOIN:
{
NewUserJoin *userJoin = (NewUserJoin*)header;
cout << "收到服务端消息:CMD_NEW_USER_JOIN,数据长度:" << userJoin->dataLength << endl;
}
break;
}
}
//发送数据
int SendData(DataHeader *header)
{
if (isRun() && header)
{
send(_sock, (const char *)header, header->dataLength, 0);
}
return SOCKET_ERROR;
}
};
#endif
- MessageHeader.hpp
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;
};
- client.cpp
#include "EasyTcpClient.hpp"
#include<thread>
bool g_bRun = true;
void cmdThread(EasyTcpClient* client)
{
while (1)
{
char cmdBuf[256] = {};
cin >> cmdBuf;
if (strcmp(cmdBuf, "exit") == 0){
g_bRun = false;
client->Close();
cout << "退出子线程" << endl;
return;
}
else if (strcmp(cmdBuf, "login") == 0){
//线程thread;
Login login;
strcpy(login.userName, "lyd");
strcpy(login.PassWord, "lydmima");
client->SendData(&login);
}
else if (strcmp(cmdBuf, "logout") == 0){
//线程thread;
Logout logout;
strcpy(logout.userName, "lyd");
client->SendData(&logout);
}
else{
cout << "不支持的命令" << endl;
}
}
}
int main()
{
EasyTcpClient client;
//client.InitSocket(); 不用定义,在连接时已经封装了定义
client.Connect((char *)"***.***.***.*", 4567);
//启动UI线程
thread t1(cmdThread, &client); //启动线程函数
t1.detach();
while (g_bRun)
{
client.OnRun();
}
client.Close();
cout << "已退出" << endl;
system("pause");
return 0;
}
最后
以上就是踏实豆芽为你收集整理的C++高并发网络架构与实现——第四篇的全部内容,希望文章能够帮你解决C++高并发网络架构与实现——第四篇所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复