在客户端:派生一个基类为CAsyncSocket的类Cconnectsock:class Cconnectsock : public CAsyncSocket
{
// Attributes
public:// Operations
public:
Cconnectsock();
virtual ~Cconnectsock();// Overrides
public:
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(Cconnectsock)
//}}AFX_VIRTUAL // Generated message map functions
//{{AFX_MSG(Cconnectsock)
// NOTE - the ClassWizard will add and remove member functions here.
//}}AFX_MSG// Implementation
protected:
};
在主窗口类的H文件clDlg.h中:
#include "connectsock.h"
/////////////////////////////////////////////////////////////////////////////
// CClDlg dialog
class CConnectsock;
class CClDlg : public CDialog
{
// Construction
public:
CClDlg(CWnd* pParent = NULL); // standard constructor
CConnectsock csock;//......................//
};
在clDlg.cpp中:if(!csock.Create()){
MessageBox("套接字创建失败!");
return(FALSE);
}
if(!csock.Connect("127.0.0.1",8000)){
MessageBox("连接失败!");
return(FALSE);
}而在服务端:
也派生一个类,并声明OnAccept函数:class CListenSocket : public CAsyncSocket
{
// Attributes
public:
//CSvDlg *svdlg;
// Operations
public:
CListenSocket();
virtual ~CListenSocket();
// Overrides
public:
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CListenSocket)
public:
virtual void OnAccept(int nErrorCode);
//}}AFX_VIRTUAL // Generated message map functions
//{{AFX_MSG(CListenSocket)
// NOTE - the ClassWizard will add and remove member functions here.
//}}AFX_MSG// Implementation
protected:
};在CListenSocket.cpp文件中:
void CListenSocket::OnAccept(int nErrorCode) 
{
// TODO: Add your specialized code here and/or call the base class
CAsyncSocket *sock=new CAsyncSocket;
this->Accept(*sock);
}
在主窗口的头文件中:
#include "ListenSocket.h"
/////////////////////////////////////////////////////////////////////////////
// CSvDlg dialog
class CListenSocket;
class CSvDlg : public CDialog
{
// Construction
public:
CSvDlg(CWnd* pParent = NULL); // standard constructor
CListenSocket lskt;
//............................................//
}
而在主窗口的.cpp文件中:
if(!lskt.Create(8000)){
MessageBox("套接字创建失败!");
return(FALSE);
}
if(!lskt.Listen(5)){
MessageBox("监听失败!");
return(FALSE);
}这就是我做的一个服务器端的监听和客户端的连接的简单测试,不过这样得出的结果是客户端始终报的是“连接失败”
请高手指点,这是为什么呀,我不知道哪里有问题,就只有这么简单的几句代码,我看都没什么错~~!
还请指教~~~!不胜感激~~