服务器的CAsyncSocket是否处于侦听状态

解决方案 »

  1.   

    服务器listen()了吗?
    你检测前面bind(),listen()的返回值,
    如果FALSE,
    调用GetLastError(),看看是什么错误.
    然后在检查客户端的,在connect()后调用GetLastError().
      

  2.   

    给你一个简单的例子先(echo服务的server和client)。
    以下是头文件:#ifndef _TF_CS_
    #define _TF_CS_#include <iostream.h>
    #include <afxsock.h>//////////////////////////////////////////////////////////////////////
    //  Class for one socket connection. class CTransSocket:public CSocket
    {
    protected:
          virtual void OnReceive ( int nErrCode ) ;
          virtual void OnClose ( int nErrCode ) ;
    } ;//////////////////////////////////////////////////////////////////////
    //  Class for whole server socket management.class CServerSocket:public CSocket
    {
    public:
          CServerSocket ( ) ;
    protected:
          virtual void OnAccept ( int nErrCode ) ;
    } ;#endif _TF_CS_下面是实现:#include "stdafx.h"
    #include "CServerSocket.h"//////////////////////////////////////////////////////////////////////
    //  Implement for the classes.void CTransSocket::OnReceive ( int nErrCode ) 
    {
          // Call the virtual function of base class
          CSocket::OnReceive ( nErrCode ) ;       // My implement here
          int iRet,i ;
          char szBuf[512] ;
          iRet = this->Receive ( szBuf,512,0 ) ;
          TRACE( "%d bytes received.\n",iRet ) ;
          for ( i=0;i<iRet;i+=1 )
          {
                  TRACE( "Char: %c\n",szBuf[i] ) ;
                  this->Send ( szBuf+i,1,0 ) ;
          }
    }void CTransSocket::OnClose ( int nErrCode )
    {
          // Call the virtual function of base class
          CSocket::OnClose ( nErrCode ) ;      // My implement here
          TRACE( "Deleting CTranssocket Object %d.\n",
                  this->m_hSocket ) ;
          delete this ;
    }CServerSocket::CServerSocket ( )
    {
    }void CServerSocket::OnAccept ( int nErrCode ) 
    {
          // Call the virtual function of base class
          TRACE( "(S)The error id is : %d\n",nErrCode ) ;
          CSocket::OnAccept ( nErrCode ) ;      // My implement here
          CTransSocket * pCTS = new CTransSocket ;
          if ( this->Accept( *pCTS ) ) ;
          else delete pCTS ;      TRACE( "Accepted!\n" ) ;