几周前我开始了 Windows 套接字编程。
到目前为止,我已经创建了一个 C 风格的客户端应用程序(基于 IOCP),它与 VC++ 2010 中的网络硬件设备进行通信。该应用程序通过 LAN 或串行端口与设备(充当服务器)异步通信:
- 创建套接字/或句柄到串行端口
- 连接到服务器
- std::vector 类型的构建命令(例如,登录命令)
- 通过套接字或串口发送命令
- 通过套接字或串口接收响应
- 断开与服务器的连接
现在我想让我现有的客户端应用程序更加面向对象,并且我提出了以下类层次结构(省略了参数):
class IClient
{
public:
virtual bool Connect() = 0;
virtual bool Disconnect() = 0;
virtual bool Send() = 0;
virtual bool Receive() = 0;
...
};
class Client : public IClient
{
public:
Client();
virtual ~Client();
virtual bool Connect() = 0;
virtual bool Disconnect() = 0;
virtual bool Send() = 0;
virtual bool Receive() = 0;
...
private:
std::string m_strConnectionSettings; // IP address, port number etc
};
class SerialClient : public Client
{
public:
bool Connect()
{
...
m_hPort = CreateFile(_T("COM3"), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
...
}
bool Disconnect()
{
...
CloseHandle(m_hPort);
...
}
bool Send()
{
...
WriteFile(m_hPort, (LPCVOID)(&vecByteData[0]), vecByteData.size(), &dwNumberOfBytesWritten, NULL);
...
}
bool Receive()
{
...
ReadFile(m_hPort, (LPVOID)&vecBuffer[0], vecBuffer.size(), &dwNumberOfBytesRead, NULL);
...
}
...
private:
HANDLE m_hPort; // Handle returned by CreateFile().
DCM m_dcb;
};
class SocketClient : public Client
{
public:
SocketClient();
virtual ~SocketClient();
virtual bool Connect() = 0;
virtual bool Disconnect() = 0;
virtual bool Send() = 0;
virtual bool Receive() = 0;
...
private:
SOCKET m_socket; // Handle returned by WSASocket().
};
class TcpClient : public SocketClient
{
public:
TcpClient();
~TcpClient();
bool Connect()
{
...
WSAConnect(m_sock, (LPSOCKADDR)&server, sizeof(server), NULL, NULL, NULL, NULL);
...
}
bool Disconnect()
{
...
closesocket(m_sock);
...
}
bool Send()
{
...
WSASend(m_sock, ...);
...
}
bool Receive()
{
...
WSARecv(m_sock, ...);
...
}
...
};
class UdpClient : public SocketClient
{
public:
UdpClient();
~UdpClient();
bool Connect();
bool Disconnect();
bool Send();
bool Receive();
...
};
然而,我对计算机网络的了解还很初级,所以我发现很难将计算机网络概念转化为 C++ 设计。例如,在上面的设计中,我不知道“Port”是从哪里来的。如果我有“Port”类和“Socket”类,那么“Port”类会包含“Socket”类还是相反或废话?
如果您能就上述设计给我一些反馈,我将不胜感激。
- 我对 Boost.Asio 做了一个非常简短的了解,看看它是如何设计的。
- 抱歉,如果我的问题含糊不清。