VC: use Windows Socket to develop applications

Source: Internet
Author: User
Tags socket error

Socket programming based on TCP (connection oriented)

I. Client:

1. Open a Socket );

2. Initiate a connection request );

3. If the connection is successful, data will be exchanged (read, write, send, and recv );

4. Data Exchange is complete. close the connection (shutdown or close );

Ii. server side:

1. Open a Socket );

2. bind the socket to the server address (bind );

3. Specify the socket as the server socket (listen) and prepare the connection request;

4. Waiting for connection requests (connect );

5. If the connection request arrives, the connection is established for data exchange (read, write, send, and recv );

6. Data Exchange is complete. close the connection (shutdown or close );

 

UDP-based Socket programming

1. Client/Server:

1. Open a Socket );

2. bind the socket to the specified server address and port (bind );

3. Data Exchange (read, write, send, and recv );

4. Data Exchange is complete. close the connection (shutdown or close );

 

Iii. MFC support for Socket:

1. Create a CAsyncSocket object;

2. send and receive data packets (SendTo and RecvFrom );

3. Connect to the server );

4. Receive connections (Listen );

5. Send and Receive streaming data (Send and Receive );

6. Close the socket );

7. GetLastError ).

 

Iv. instances: online chat tools

 

 

Client:

 

 

1 ,....

2. Use the Class Wizard to overload the CAsyncSocket class and generate a new MySocket class ..

3. Use the Class Wizard to reload the OnReceive (int nErrorCode), OnSend (int nErrorCode), and OnConnect (int nErrorCode) functions of CAsyncSocket.

Void MySocket: OnReceive (int nErrorCode)

{

// TODO: Add your specialized code here and/or call the base class

// Get the pointer of the dialog box

CTestApp * pApp = (CTestApp *) AfxGetApp ();

CTestDlg * pDlg = (CTestDlg *) pApp-> m_pMainWnd;

// Insert a message to the edit box

Char * pbuf = new char [4096];

Int ibufsize = 4096;

Int ircvd;

CString strrecvd;

Ircvd = Receive (pbuf, ibufsize );

If (ircvd = SOCKET_ERROR)

{

PDlg-> MessageBox ("SOCKET_ERROR ");

}

Else

{

Pbuf [ircvd] = NULL;

PDlg-> m_recmsg + = "server :";

PDlg-> m_recmsg + = pbuf;

PDlg-> m_recmsg + = "\ r \ n ";

PDlg-> RefreshScreen ();

}

Delete pbuf;

CAsyncSocket: OnReceive (nErrorCode );

}

 

Void MySocket: OnSend (int nErrorCode)

{

// TODO: Add your specialized code here and/or call the base class

CAsyncSocket: OnSend (nErrorCode );

}

 

Void MySocket: OnConnect (int nErrorCode)

{

// TODO: Add your specialized code here and/or call the base class

CTestApp * pApp = (CTestApp *) AfxGetApp ();

CTestDlg * pDlg = (CTestDlg *) pApp-> m_pMainWnd;

 

Int iResult = nErrorCode;

CString buffer;

 

Int namelen;

If (iResult! = 0)

{

Buffer. Format ("failed to connect to the server. \ R \ n ");

PDlg-> m_recmsg + = buffer;

}

Else

{

Namelen = sizeof (sockaddr_in );

Buffer. Format ("successfully connected to the server % s: % d. \ r \ n", pDlg-> m_ipstr, pDlg-> m_port );

PDlg-> m_recmsg + = buffer;

PDlg-> GetDlgItem (IDC_SEND)-> EnableWindow (TRUE );

PDlg-> GetDlgItem (IDOK)-> EnableWindow (TRUE );

}

PDlg-> RefreshScreen ();

CAsyncSocket: OnConnect (nErrorCode );

}

4. In the C * Dlg class

Header file:

# Include "MySocket. h"

 

MySocket m_socket;

CString m_ipstr;

 

 

In the. CPP file:

 

Void CTestDlg: OnSend ()

{

// TODO: Add your control notification handler code here

Int ilen;

Int isent;

UpdateData (TRUE );

If (m_msg! = "")

{

Ilen = m_msg.GetLength ();

 

Isent = m_socket.Send (LPCTSTR (m_msg), ilen );

If (isent = SOCKET_ERROR)

{

MessageBox ("connection failed. Please try again! ");

// Connect = false;

}

Else

{

M_recmsg + = "client:" + m_msg;

M_recmsg + = "\ r \ n ";

UpdateData (FALSE );

}

}

}

Void CTestDlg: RefreshScreen ()

{

UpdateData (false );

}

Void CTestDlg: OnConnect ()

{

If (! AfxSocketInit ())

{

AfxMessageBox ("IDP_SOCKETS_INIT_FAILED ");

Return;

}

GetDlgItemText (IDC_IPADDRESS1, m_ipstr );

M_socket.m_hSocket = INVALID_SOCKET;

UpdateData (true );

 

BOOL flag = m_socket.Create ();

If (! Flag)

{

AfxMessageBox ("socket error ");

Return;

}

M_socket.Connect (m_ipstr, m_port );

}

 

Void CTestDlg: OnOK ()

{

// TODO: Add extra validation here

M_socket.Close ();

CDialog: OnOK ();

}

 

 

Server:

 

 

1 ,....

2. Use the Class Wizard to overload the CAsyncSocket class and generate a new MySocket class ..

3. Use the Class Wizard to reload the OnReceive (int nErrorCode) and OnSend (int nErrorCode) functions of CAsyncSocket.

 

Void MySocket: OnReceive (int nErrorCode)

{

// TODO: Add your specialized code here and/or call the base class

CTestApp * pApp = (CTestApp *) AfxGetApp ();

CTestDlg * pDlg = (CTestDlg *) pApp-> m_pMainWnd;

// Insert a message to the list box

Char * pbuf = new char [4096];

Int ibufsize = 4096;

Int ircvd;

CString strrecvd;

Ircvd = Receive (pbuf, ibufsize );

If (ircvd = SOCKET_ERROR)

{

PDlg-> MessageBox ("SOCKET_ERROR ");

}

Else

{

Pbuf [ircvd] = NULL;

PDlg-> m_msg + = "client :";

PDlg-> m_msg + = pbuf;

PDlg-> m_msg + = "\ r \ n ";

PDlg-> RefreshScreen ();

}

Delete pbuf;

CAsyncSocket: OnReceive (nErrorCode );

}

 

Void MySocket: OnSend (int nErrorCode)

{

// TODO: Add your specialized code here and/or call the base class

CAsyncSocket: OnSend (nErrorCode );

}

 

 

4. Create a New MyServerSocket class and add MySocket * m_socket; that is, the socket pointer after receiving the request.

 

MySocket * m_socket;

 

Void CMyServerSocket: OnAccept (int nErrorCode)

{

// TODO: Add your specialized code here and/or call the base class

CTestApp * pApp = (CTestApp *) AfxGetApp ();

CTestDlg * pDlg = (CTestDlg *) pApp-> m_pMainWnd;

// Display the connection message

PDlg-> m_msg = "connecting the client to the server ";

PDlg-> m_msg + = "\ r \ n ";

PDlg-> RefreshScreen ();

PDlg-> GetDlgItem (IDC_SEND)-> EnableWindow (TRUE );

PDlg-> GetDlgItem (IDOK)-> EnableWindow (TRUE );

 

MySocket * psocket = new MySocket ();

If (Accept (* psocket ))

{

Psocket-> AsyncSelect (FD_READ );

M_socket = psocket;

}

Else

{

Delete psocket;

}

CAsyncSocket: OnAccept (nErrorCode );

}

5. C * Dlg class

 

Void CTestDlg: RefreshScreen ()

{

UpdateData (false );

}

Void CTestDlg: OnListen () // create a server

{

// TODO: Add your control notification handler code here

UpdateData (true );

If (! AfxSocketInit ())

{

AfxMessageBox ("IDP_SOCKETS_INIT_FAILED ");

Return;

}

BOOL flag = m_serversocket.Create (m_port );

If (! Flag)

{

AfxMessageBox ("socket error ");

Return;

}

Flag = m_serversocket.Listen (1 );

If (! Flag)

{

AfxMessageBox ("socket error ");

Return;

}

SetDlgItemText (IDC_LISTEN, "listening ");

}

 

Void CTestDlg: OnSend ()

{

// TODO: Add your control notification handler code here

Int ilen;

Int isent;

UpdateData (TRUE );

If (m_sendmsg! = "")

{

Ilen = m_sendmsg.GetLength ();

 

Isent = m_serversocket.m_socket-> Send (LPCTSTR (m_sendmsg), ilen );

If (isent = SOCKET_ERROR)

{

MessageBox ("connection failed. Please try again! ");

}

Else

{

M_msg + = "server:" + m_sendmsg;

M_msg + = "\ r \ n ";

UpdateData (FALSE );

}

}

}

 

 

Void CTestDlg: OnOK ()

{

// TODO: Add extra validation here

M_sendmsg = "server logout ";

UpdateData (false );

OnSend ();

M_serversocket.Close ();

CDialog: OnOK ();

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.