MFC CSocket简单C/S通信

来源:互联网 发布:北大青鸟java要加班吗 编辑:程序博客网 时间:2024/05/17 09:35

网络编程需要注意的

0.编程中套接字应该分为三类,一类为客户端套接字,一类为服务器套接字,一类为Accept返回的套接字。这个应该时刻有这个认识

1.三种套接字类在连接成功后都会马上自动进入各自类的OnSend,都没有进入OnConnect。(自己测试确实是这样,跟别人描述不符,不知道怎么回事),进入OnSend,表示可以发送数据了

2.服务器跟客户端交互靠的是Accept返回的套接字而不是服务器套接字,服务器只有接受客户端连接作用,其他事就都是靠Accept返回的套接字去做了

有了三条意识就知道一个简单网络通信应该客户端派生一个socket,服务器程序有两个socket派生类。

客户端:

[cpp] view plaincopy
  1. void CClientSocket::OnSend(int nErrorCode)  
  2. {  
  3.     char *str=_T("我是客户端的liunian");  
  4.     if(!Send(str,strlen(str)+1))  
  5.     {  
  6.         AfxMessageBox("发送错误");  
  7.     }  
  8.     CSocket::OnSend(nErrorCode);  
  9. }  
  10.   
  11. void CClientSocket::OnReceive(int nErrorCode)  
  12. {  
  13.     char buff[1000];  
  14.     int count;  
  15.     count=Receive(buff,1000);  
  16.     buff[count]=0;  
  17.     AfxMessageBox(buff);  
  18.     CSocket::OnReceive(nErrorCode);  
  19. }  
  20.   
  21. bool CClientSocket::ConnectServer(LPCTSTR lpszHostAddress,UINT nHostPort)  
  22. {  
  23.     if (!Create())  
  24.     {  
  25.         Close();  
  26.         AfxMessageBox(_T("创建套接字错误!!"));  
  27.         return false;  
  28.     }  
  29.     if (!Connect(lpszHostAddress,nHostPort))  
  30.     {  
  31.         Close();  
  32.         AfxMessageBox(_T("网络连接错误!请重新检查服务器地址的填写是否正确?"));  
  33.         return false;  
  34.     }  
  35.     return true;  
  36. }  


服务器端:

[cpp] view plaincopy
  1. void CServerSocket::OnAccept(int nErrorCode)  
  2. {  
  3.     Accept(m_connectSocket);  
  4.     CSocket::OnAccept(nErrorCode);  
  5.   
  6. }  
  7.   
  8. bool CServerSocket::OpenServer(UINT nHostPort)  
  9. {  
  10.     Create(nHostPort);  
  11.     Listen();  
  12.     return true;  
  13. }  

[cpp] view plaincopy
  1. void CConnectSocket::OnReceive(int nErrorCode)  
  2. {  
  3.     char buff[1000];  
  4.     int count;  
  5.     count=Receive(buff,1000);  
  6.     buff[count]=0;  
  7.     AfxMessageBox(buff);  
  8.     CSocket::OnReceive(nErrorCode);  
  9. }  
  10.   
  11. void CConnectSocket::OnSend(int nErrorCode)  
  12. {  
  13.     char *str=_T("服务器发来的liunian");  
  14.     Send(str,strlen(str)+1);  
  15.     CSocket::OnSend(nErrorCode);  
  16. }  
程序:

[cpp] view plaincopy
  1. //函数都没有命名  
  2. void CMFCSocketDlg::OnBnClickedButton1()//开启服务器  
  3. {  
  4.     m_serverSocket.OpenServer(6767);  
  5. }  
  6.   
  7. void CMFCSocketDlg::OnBnClickedButton2()//连接服务器  
  8. {  
  9.     m_clientSocket.ConnectServer(_T("111.76.27.230"),6767);  
  10. }  
0 0