先派生了一个CAsyncSocket的新类CNewSocket,声明和定义和以下几个函数:
         void OnClose(int nErrorCode);
void OnConnect(int nErrorCode);
void OnAccept(int nErrorCode);
void OnReceive(int nErrorCode);
void OnSend(int nErrorCode);
如void CNewSocket::OnConnect(int nErrorCode)
{
if(nErrorCode==0)
   ((CSever_ClientDlg*)m_pWnd)->OnConnect();
}
然后建立了一个基于TCP-IP通讯的类,将服务器和客户端封装到一个类中,现在一个服务器只能连接一个客户端,当再运行一客户端时,类的Accept函数就报错,是不是正在通讯的第一个客户端正在使用套接字,后面无法建立连接,请教,该如何让解决可与多个客户端通讯?十分感谢。
主要代码如下:
void CSever_ClientDlg::OnBconnect()                           连接按键
{
// TODO: Add your control notification handler code here
   UpdateData(true);
   if(m_Type==0)         //客户端
   {
 
  m_sConnectSocket.Create();                       //客户端产生一缺省套接字
  m_sConnectSocket.Connect(m_ServerIP,m_Port);     //客户端与服务器端连接

   }
   else                 //服务器
   {
  m_sListenSocket.Create(m_Port);                  //服务器产生一个绑定端口的套接字
  m_sListenSocket.Listen(5);                       //服务器监听
  AfxMessageBox("服务器已启动,开始监听");
   }
}
void CSever_ClientDlg::OnAccept()
{   
    m_sListenSocket.Accept(m_sConnectSocket,NULL,NULL);
}
void CSever_ClientDlg::OnReceive()
{
char*pBuf=new char[1025];
int iBufSize=1024;
int iRcvd;
CString strRecvd;
iRcvd=m_sConnectSocket.Receive(pBuf,iBufSize);
if(iRcvd==SOCKET_ERROR)
{
}
else
{
 pBuf[iRcvd]=NULL;
 strRecvd=pBuf;
 m_ctrlRecvd.AddString(strRecvd);
 UpdateData(false);
}
}
void CSever_ClientDlg::OnBsend() 
{
// TODO: Add your control notification handler code here
int iLen;
int iSent;
UpdateData(true);

iLen=m_strMessage.GetLength();
iSent=m_sConnectSocket.Send(LPCSTR(m_strMessage),iLen);
m_strMessage.Empty();
if(iSent!=SOCKET_ERROR)
{
AfxMessageBox("发送成功!");
}
else
{
AfxMessageBox("不能发送!");

}

}
void CSever_ClientDlg::OnClose()
{
 m_sConnectSocket.Close();
 m_sListenSocket.Close();
 if(m_Type==0)                        //客户端
 {
 AfxMessageBox("和服务器断开");
 }
 else                                //服务器
 {
 AfxMessageBox("客户已下线");
 }}

解决方案 »

  1.   

    你都只有一个m_sConnectSocket,当然只能连接一个了。
    每次Accept的时候,都需要新创建一个套接字。服务端永远是维护一个容器,比如数组,用来保存所有与客户端连接的套节字(这是最基本的服务端特性之一,当然,监听是最具服务端特性的了),你的服务端完全不像是一个服务端。
      

  2.   

    简单一点,服务器多线程,一个监听线程,accept不断的接收到来的connect连接,accept返回的socket用户和客户端进行IO通讯,服务器端须动态维护客户端的SOCKET链表