network terminology
Synchronous: refers to the communication mode in which the sender sends the data and waits for the response from the receiver before sending the next data packet.
Asynchronous: refers to the communication in which the sender sends the next data packet without waiting for the receiver to respond. Blocking
: When calling a function, it will not return until the function completes the operation; otherwise, it will always block on the call.
Non-blocking: When calling an operation, it will return immediately regardless of whether the operation is successful or not, and will not hang on the operation.
1. CAsyncSocket class
Provides an event-based I/O asynchronous model
1.create
This method is used to create a Windows socket and attach it to the CAsyncSocket class object
BOOL Create(UINT nSocketPort=0,int nSocketType=SOCK_STREAM,long IEvent=FD_READ|FD_WRITE|FD_OOB|FD_ACCEPT|FD_CONNECT|FD_CLOSE,LPCTSTR lpszSocketAddress =NULL);
nSocketPort: socket port, if it is 0, the system automatically selects a port
nSocketType: socket type, if SOCK_STREAM=stream socket, SOCK_DGRAM=datagram socket
IEvent: socket can Processed network events
FD_READ: Triggered when there is data in the socket to be read
FD_WRITE: Triggered when data is written to the socket
FD_OOB: Triggered when out-of-band data is
received FD_ACCEPT: When a connection request is received Trigger event
FD_CONNECT: Trigger event when connection is complete
FD_CLOSE: Trigger event when socket is closed
lpszSocketAddress: IP address of the socket
2.GetLastError
This method is used to get the status information of the last operation failure
static int GetLastError();
3.GetPeerName
This method is used to get the IP address information in the socket connection
BOOL GetPeerName(CString&rPeerAddress,UINT&rPeerPort);
BOOL GetPeerName(SOCKADDR*lpSockAddr,int*lpSockAddrLen);
rPeerAddress: used to receive the IP address returned by the function
rPeerPort: used to record the port No.
lpSockAddr: a socketaddr structure pointer, used to record the socket name
lpSockAddrLen: used to determine the size of lpSocketAddr
4.Accept
This method is used to accept the client's connection
virtual BOOL Accept(CAsyncSocket&rConnectedSocket,SOCKADDR*lpsockAddr=NULL,int*lpSockAddrLen=NULL);
rConnectedSocket: the socket reference corresponding to the current connection
lpSockAddr: a sockaddr structure pointer, used to record the socket Address
lpSockAddrLen: used to determine the size of lpsockaddr
5.bind
This method is used to bind the IP address and port number to the socket
BOOL Bind(UINT nSocketPort,LPCTSTR lpszSocketAddress=NULL);
BOOL Bind(const SOCKADDR*lpSockAddr,int nSockAddrLen);
nSocketport: socket port
lpszSocketAddress:IP Address
lpSockADdr: a sockaddr structure pointer
nSockAddrLen: used to determine the size of lpsockAddr
6.connect
This method is used to send a connection request
BOOL Connect(LPCTSTR lpszHostAddress, UINT nHostPort);
BOOL Connect(const SOCKADDR* lpSockAddr, int nSockAddrLen);
lpszHostAddress: the IP address or URL
of the host nHostPort: the port of the host
lpSockADdr: a pointer to a sockaddr structure
nSockAddrLen : used to determine the size of lpsockAddr
7.close
This method is used to close the socket
virtual void Close();
8.Listen
This method is used to put the socket in listening mode
BOOL Listen(int nConnectionBacklog=5);
nConnectionBacklog: maximum queue length waiting for connections
9.receive
This method is used to receive data in streaming sockets
virtual int Receive(void* lpBuf, int nBuflen, int nFlags=0);
lpBuf: buffer to receive data
nBufLen: determine the length of the buffer
nFlags: determine the call of the function Mode, MSG_PEEK=represents viewing incoming data, data is copied to the receive buffer, but not removed from the input queue; MSG_OOB=processes out-of-band data.
10.ReceiveFrom
This method is used to receive data from the packet socket
int ReceiveFrom(void*lpBuf,int nBufLen,CString&rSocketAddress,UINT&rSocktPort,int nFlags=0);
int RecerveFrom(void *lpBuf,int nBufLen,SOCKADDR* lpSockAddr,int *lpSockAddrLen ,int Flags=0);
lpBuf: buffer for receiving data
nBufLen: buffer size
rSocketAddress: destination (IP address) for receiving datagrams
rSocketPort: used to record the port number
lpSockAddr: a pointer to a sockaddr structure for Record socket address information
lpSockAddrLen: used to determine the size of lpSockAddr
nFlags: function calling mode
11.send
This method is used to send data to the streaming socket
virtual Send(const void* lpBuf, int nBufLen, int nFlags=0);
lpBuf: buffer to send data
nBufLen: buffer size
nFlags: function call method
12.sendTo
This method is used to send data on stream socket or packet socket
int SendTo(const void*lpBuf,int nBuflen,UINT nHostPort,LPCTSTR lpszHostAddress=NULL,int nFlags=0);
int Sendto(const void* lpBuf,int nBufLen,const SOCKADDR* lpSockAddr,int nSockAddrLen,int nFlags=0);
lpBuf: buffer to send data
nBufLen: buffer size
nHostPort: host port number
lpszHostAddress: host address
lpSockAddr: a sockaddr structure pointer
nSockAddrLen: lpsockAddr The size of
nFlags: how the function is called
13.shutDown
This method is used to disconnect the sending or receiving of data on the socket.
BOOL ShutDown(int nHow=sends);
nHow: used to determine the behavior of the function, 0 means not allowed to receive, 1 means not allowed to send, 2 means not allowed receive and send
14.OnAccept
This event is triggered when the socket receives a connection request
virtual void OnAccept(int nErrorCode);
nErrorCode: error code
15.OnClose
The event is fired when the socket is closed
virtual void OnClose(int nErrorCode);
16.OnConnect
This event is triggered when the socket is connected
virtual OnConnect(int nErrorCode);
17.OnReiceive
This event is triggered when the socket has data received
virtual OnReiceive(int nErrorCode);
18.Unsend
This event is triggered when the socket sends data
virtual Onsend(int nErrorCode);
2. CSocket class
The CSocket class is derived from the CAsyncSocket class, which encapsulates socket functions at a higher level and provides synchronization technology.
1.create
This method is used to create a Windows socket and attach it to the CSocket class object
BOOL Create(UINT nSocketPort=0,int nSocketType=SOCK_STREAM ,LPCTSTR lpszSocketAddress=NULL);
nSocketPort: socket port, if 0, The system automatically selects a port
nSocketType: socket type, if SOCK_STREAM=stream socket, SOCK_DGRAM=datagram socket
lpszSocketAddress: socket IP address
2.Attach
This method is used to attach a socket handle to the CSocket class object
BOOL Atach(SOCKET hSocket);
hSocket: socket handle
3.FromHandle
This method obtains the CSocket object pointer according to the socket handle
static CSocket* PASCAL FromHandle(SOCKET hSocket);
hSocket: socket handle
Return value: CSocket object pointer
4.lsBlocking
This method is used to determine whether the socket is in blocking mode
BOOL lsBlocking();
return value: 0=non-blocking, non-0=blocking
5.CancelBlockingCall
This method is used to cancel the blocking mode of the socket
void CancelBlockingCall();
Third, the client implementation process
1. Create a dialog box, project client
2. Initialize the socket in the InitInstance method
[cpp] view plain copy
- BOOL CClientApp::InitInstance()
- {
- WSADATA wsd; //Define the WSADATA object
- WSAStartup(MAKEWORD(2,2),&wsd); //Initialize the socket
- }
3. Derive a subclass CClientSocket from the CSocket class, and add the m_pDialog member to this class
[cpp] view plain copy
- CClientDlg *m_pDialog;//Add member variables
4. Add the SetDialog method in CClientSocket for social member variables
[cpp] view plain copy
- void CClientSocket::SetDialog(CClientDlg *pDialog)
- {
- m_pDialog = pDialog;//Set member variables
- }
5. Rewrite the OnReceive method of the CClientSocket class and call this method when the socket has data to receive
[cpp] view plain copy
- void CClientSocket::OnReceive(int nErrorCode)
- {
- CSocket::OnReceive(nErrorCode);
- if (m_pDialog != NULL)//Determine whether the member variable is empty
- m_pDialog->ReceiveText();//Call the ReceiveText method of the dialog class to receive data
- }
6. Add the following member variables to the dialog box
[cpp] view plain copy
- CClientSocket m_SockClient;//Define socket member variables
- CString m_Name;//Define a string variable
7. Add the ReceiveText method to the dialog class to receive data
[cpp] view plain copy
- void CClientDlg::ReceiveText()
- {
- char buffer[BUFFERSIZE];//Define the buffer for receiving data
- int len = m_SockClient.Receive(buffer,BUFFERSIZE);//Start receiving data
- if (len != -1)
- {
- buffer[len] = '\0';//Set the end marker
- m_List.AddString(buffer);//Add the received information to the list
- }
- }
8. Create the socket when the dialog is initialized
[cpp] view plain copy
- m_SockClient.Create();//Create a socket
- m_SockClient.SetDialog(this);//Set the member variables of the socket
9. Process the "Login" button and start logging into the server
[cpp] view plain copy
- void CClientDlg::OnLogin()
- {
- CString strIP, strPort;//Define two string variables
- UINT port ;//Define an integer port variable
- m_ServerIP.GetWindowText(strIP);//Get server IP
- m_NickName.GetWindowText(m_Name);//Get the user's nickname
- m_ServerPort.GetWindowText(strPort);//Get the port
- if (strIP.IsEmpty() || strPort.IsEmpty() || m_Name.IsEmpty())
- {
- MessageBox("Please set server information","Prompt");
- return;
- }
- port = atoi(strPort);//Convert port string to integer
- if (m_SockClient.Connect(strIP,port))//Start connecting to the server
- {
- MessageBox("Connect to the server successfully!","Prompt");
- CString str;
- str.Format("%s----->%s",m_Name,"Enter the chat room");
- m_SockClient.Send(str.GetBuffer(0),str.GetLength());//Send data to the server, and then forward it by the server
- }
- else
- {
- MessageBox("Failed to connect to server!","Prompt");
- }
- }
10. Process the "Send" button, send data to the server, and the server forwards the data
[cpp] view plain copy
- void CClientDlg::OnSendText()
- {
- CString strText, strInfo;//Define two string variables
- m_Text.GetWindowText(strText);//Get the sent content
- if (!strText.IsEmpty() && !m_Name.IsEmpty())
- {
- strInfo.Format("%s says: %s",m_Name,strText);//Set the text to send
- // start sending data
- int len = m_SockClient.Send(strInfo.GetBuffer(strInfo.GetLength()),strInfo.GetLength());
- }
- }
Fourth, the server implementation process
1. Create a dialog box, project Server
2. Initialize the socket in the InitInstance method
[cpp] view plain copy
- BOOL CClientApp::InitInstance()
- {
- //Initialize the socket
- WSADATA wsd;
- AfxSocketInit(&wsd);
- }
3. Derive a subclass CServerSocket from the CSocket class, and add the m_pDlg member to this class
[cpp] view plain copy
- CServerDlg *m_pDlg;//Add member variables
4. Add the SetDialog method in CServerSocket for social member variables
[cpp] view plain copy
- void CServerSocket::SetDialog(CServerDlg *pDialog)
- {
- m_pDlg= pDialog;//Set member variables
- }
5. Rewrite the OnAccept method of the CServerSocket class to accept the connection when the socket has a connection request
[cpp] view plain copy
- void CServerSocket::OnAccept(int nErrorCode)
- {
- CSocket::OnAccept(nErrorCode);
- if (m_pDlg)
- m_pDlg->AcceptConnect();
- }
6. Derive a new class CClientSocket from the CSocket class again, and define the member variable m_pDlg in this class
[cpp] view plain copy
- CServerDlg* m_pDlg;
7. Add the SetDlialog function to the CClientSocket class and assign a value to the m_pDlg member variable
[cpp] view plain copy
- void CClientSocket::SetDialog(CServerDlg* pDialog)
- {
- m_pDlg = pDialog;
- }
8. Rewrite the OnReceive method of the CClientSocket class to receive data when the socket has data
[cpp] view plain copy
- void CClientSocket::OnReceive(int nErrorCode)
- {
- CSocket::OnReceive(nErrorCode);
- if(m_pDlg)
- {
- m_pDlg->ReceiveData(*this);
- }
- }
9. Add the following member variables to the dialog class
[cpp] view plain copy
- CPtrList m_socketlist;//Define the socket list container
- CServerSocket m_ServerSock;//Define socket
10. Add the AcceptConnect method to the dialog class to accept the connection from the client
[cpp] view plain copy
- void CServerDlg::AcceptConnect()
- {
- CClientSocket* psocket = new CClientSocket();//Create a socket
- psocket->SetDialog(this);//Set socket member variables
- if (m_ServerSock.Accept(*psocket))//Accept socket connection
- m_socketlist.AddTail(psocket);//Add the socket to the list container
- else
- delete psocket;//Connection failed, release the socket
- }
11. Add the ReceiveData method to the dialog class to receive data
[cpp] view plain copy
- void CServerDlg::ReceiveData(CSocket &socket)
- {
- char bufferdata[BUFFERSIZE];
- int len = socket.Receive(bufferdata,BUFFERSIZE);//Start receiving data
- if (len != -1)//Determine whether data is received
- {
- bufferdata[len] = 0;//Set data end marker
- POSITION pos = m_socketlist.GetHeadPosition();//Get the first position of the container list
- while (pos != NULL)//traverse the container list
- {//Get the specified socket in the container list
- CClientSocket* socket = (CClientSocket*)m_socketlist.GetNext(pos);
- if (socket != NULL)//Determine whether the socket is empty
- socket->Send(bufferdata,len);//Send data to the socket
- }
- }
- }
12. Process the "Settings" button, create and start listening sockets
[cpp] view plain copy
- void CServerDlg::OnConfig()
- {
- m_ServerSock.SetDialog(this);//Set socket member variables
- CString strPort,strIP;//Define two string variables
- m_ServerPort.GetWindowText(strPort);//Get the port string
- m_ServerIP.GetWindowText(strIP);//Get the service IP
- if (!strPort.IsEmpty() && !strIP.IsEmpty())
- {
- UINT port = atoi(strPort);
- m_ServerSock.Create(port,SOCK_STREAM,strIP);//Create a socket
- BOOL ret = m_ServerSock.Listen();//Put the socket in listening mode
- if (ret)
- MessageBox("Set successfully!","Prompt");
- }
- }