WinSock provides TCP (Transmission Control Protocol) support. We can establish a connection with the host with the specified IP address through the TCP protocol, and use the established connection to exchange data in two directions. Using CSocket to manipulate connected data exchange is very simple, but in the connected communication, one party must assume the server role and wait for the connection request of the other party (customer, therefore, the server needs to establish a listener interface, and then wait for the connection on this interface. After a connection is established, a new interface is generated for communication. After creating a set of interfaces, the customer can create a connection by simply calling the connection function. The order of data transmission, transmission, and receipt for connected communications is guaranteed. Function call sequence of both parties.
The following code demonstrates how to establish a connection and send/Receive data:
/*
The server is on the port6802. Wait for the connection. When the connection is established, the listener interface is closed.
Client-to-server port6802 initiate a connection request
*/
BOOL CMy63_s1_serverDlg: OnInitDialog ()
{
CDialog: OnInitDialog ();
CSocket sockListen;
// Create a local Interface
SockListen. Create (6802, SOCK_STREAM, "127.0.0.1 ");
// Bind Parameters
SockListen. Bind (6802, "127.0.0.1 ");
SockListen. Listen (5 );
// Wait for the connection request. m_sockSend is the member variable for communication.
SockListen. Accept (m_sockSend );
// Disable the listener set Interface
SockListen. Close ();
// Start the timer and send data regularly
SetTimer (1,3000, NULL );