网络编程需要注意的
0.编程中套接字应该分为三类,一类为客户端套接字,一类为服务器套接字,一类为Accept返回的套接字。这个应该时刻有这个认识
1.三种套接字类在连接成功后都会马上自动进入各自类的OnSend,都没有进入OnConnect。(自己测试确实是这样,跟别人描述不符,不知道怎么回事),进入OnSend,表示可以发送数据了
2.服务器跟客户端交互靠的是Accept返回的套接字而不是服务器套接字,服务器只有接受客户端连接作用,其他事就都是靠Accept返回的套接字去做了
有了三条意识就知道一个简单网络通信应该客户端派生一个socket,服务器程序有两个socket派生类。
客户端:
void CClientSocket::OnSend(int nErrorCode) { char *str=_T("我是客户端的liunian"); if(!Send(str,strlen(str)+1)) { AfxMessageBox("发送错误"); } CSocket::OnSend(nErrorCode); } void CClientSocket::OnReceive(int nErrorCode) { char buff[1000]; int count; count=Receive(buff,1000); buff[count]=0; AfxMessageBox(buff); CSocket::OnReceive(nErrorCode); } bool CClientSocket::ConnectServer(LPCTSTR lpszHostAddress,UINT nHostPort) { if (!Create()) { Close(); AfxMessageBox(_T("创建套接字错误!!")); return false; } if (!Connect(lpszHostAddress,nHostPort)) { Close(); AfxMessageBox(_T("网络连接错误!请重新检查服务器地址的填写是否正确?")); return false; } return true; }
void CServerSocket::OnAccept(int nErrorCode) { Accept(m_connectSocket); CSocket::OnAccept(nErrorCode); } bool CServerSocket::OpenServer(UINT nHostPort) { Create(nHostPort); Listen(); return true; }
void CConnectSocket::OnReceive(int nErrorCode) { char buff[1000]; int count; count=Receive(buff,1000); buff[count]=0; AfxMessageBox(buff); CSocket::OnReceive(nErrorCode); } void CConnectSocket::OnSend(int nErrorCode) { char *str=_T("服务器发来的liunian"); Send(str,strlen(str)+1); CSocket::OnSend(nErrorCode); }程序:
//函数都没有命名 void CMFCSocketDlg::OnBnClickedButton1()//开启服务器 { m_serverSocket.OpenServer(6767); } void CMFCSocketDlg::OnBnClickedButton2()//连接服务器 { m_clientSocket.ConnectServer(_T("111.76.27.230"),6767); }