class CClientSocket : public CSocket { // Attributes public: // Operations public: CClientSocket(CChatDlg* pdlg); virtual ~CClientSocket(); // Overrides public: BOOL m_bFirst; CChatDlg* pDlg; // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CClientSocket) public: virtual void OnReceive(int nErrorCode); //}}AFX_VIRTUAL // Generated message map functions //{{AFX_MSG(CClientSocket) // NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG // Implementation protected: }; m_bFirst和pDlg是自定义的两个类别成员, 其作用见下文。 class CServerSocket : public CSocket { // Attributes public: // Operations public: CServerSocket(CChatDlg* pdlg); virtual ~CServerSocket(); // Overrides public: CChatDlg* pDlg; // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CServerSocket) public: virtual void OnReceive(int nErrorCode); //}}AFX_VIRTUAL // Generated message map functions //{{AFX_MSG(CServerSocket) // NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG // Implementation protected: }; 然后,在CChatDlg类中加入对 按钮Listen的处理函数如下: void CChatDlg::OnListen() { pClientSocket = new CClientSocket(this); if(pClientSocket != NULL) { if(!pClientSocket->Create(SNMP_SOCKET_PORT, SOCK_DGRAM)) AfxMessageBox("Can not create ClientSocket !"); else ::EnableWindow(GetDlgItem(IDC_LISTEN)-> m_hWnd,FALSE); } else { AfxMessageBox("Can not new ClientSocket !"); } } 注意:SNMP_SOCKET_PORT应设为161。 然后,在CClientSocket中加入 虚函数OnReceive的实作内容: void CClientSocket::OnReceive(int nErrorCode) { CSocket::OnReceive(nErrorCode); unsigned char tmp[MAXTMPSIZE]; //MAXTMPSIZE是自定义宏,可为1024; int i; int RecNum; UINT ClientPort; CString ClientAddress; if(m_bFirst) { m_bFirst = false; RecNum = ReceiveFrom(tmp, MAXTMPSIZE, ClientAddress, ClientPort); if(RecNum > 0) { TRACE("Received from client, %d bytes :\n", RecNum); for(i=0; i<RecNum; i++) { if(i%10==0) TRACE("\n%5d,", tmp[i]); else TRACE("%5d,", tmp[i]); } TRACE("\n\n"); pDlg->CreateServerSocket(ClientAddress, ClientPort); pDlg->Send(true, tmp, RecNum); } else AfxMessageBox("Error: fail to Receive from client the first time!"); } else { RecNum = Receive(tmp, MAXTMPSIZE); if(RecNum > 0) { TRACE("Received from client, %d bytes :\n", RecNum); for(i=0; i<RecNum; i++) { if(i%10==0) TRACE("\n%5d,", tmp[i]); else TRACE("%5d,", tmp[i]); } TRACE("\n\n"); pDlg->Send(true, tmp, RecNum); } else AfxMessageBox("Error: fail to Receive from client!"); } if(RecNum <= 0) { AfxMessageBox("Error: fail to Receive from client !"); return; } } |