sock无法初始化!", AfxGetAppName(), MB_OK|MB_ICONSTOP);
WSACleanup();
return; }
else
WSACleanup();
if (gethostname(chInfo, sizeof(chInfo)))
{ ReportWinsockErr("\n无法获取主机!\n ");
return; }
CString csWinsockID = "\n==>>服务器功能开启在端口:No. ";
csWinsockID += itoa(m_pDoc->m_nServerPort, chInfo, 10);
csWinsockID += "\n";
PrintString(csWinsockID); //在
程序视图显示提示信息的函数,读者可自行创建
m_pDoc->m_hServerSocket=socket(PF_INET, SOCK_STREAM, DEFAULT_PROTOCOL);
//创建服务器端Socket,类型为SOCK_STREAM,面向连接的通信
if (m_pDoc->m_hServerSocket == INVALID_SOCKET)
{ ReportWinsockErr("无法创建服务器socket!");
return;}
m_pDoc->m_sockServerAddr.sin_family = AF_INET;
m_pDoc->m_sockServerAddr.sin_addr.s_addr = INADDR_ANY;
m_pDoc->m_sockServerAddr.sin_port = htons(m_pDoc->m_nServerPort);
if (bind(m_pDoc->m_hServerSocket, (LPSOCKADDR)&m_pDoc->m_sockServerAddr,
sizeof(m_pDoc->m_sockServerAddr)) == SOCKET_ERROR) //与选定的端口绑定
{ReportWinsockErr("无法绑定服务器socket!");
return;}
iErrorCode=WSAAsyncSelect(m_pDoc->m_hServerSocket,m_hWnd,
WM_SERVER_ACCEPT, FD_ACCEPT);
//设定服务器相应的网络事件为FD_ACCEPT,即连接请求,
// 产生相应传递给窗口的消息为WM_SERVER_ACCEPT
if (iErrorCode == SOCKET_ERROR)
{ ReportWinsockErr("WSAAsyncSelect设定失败!");
return;}
if (listen(m_pDoc->m_hServerSocket, QUEUE_SIZE) == SOCKET_ERROR) //开始监听客户连接请求
{ReportWinsockErr("服务器socket监听失败!");
m_pParentMenu->EnableMenuItem(ID_SERVER_OPEN, MF_ENABLED);
return;}
m_bServerIsOpen = TRUE; //监视服务器是否打开的变量
return;
}
响应客户发送聊天文字到服务器:ON_MESSAGE(WM_CLIENT_READ, OnClientRead)
LRESULT OnClientRead(WPARAM wParam, LPARAM lParam)
{
int iRead;
int iBufferLength;
int iEnd;
int iRemainSpace;
char chInBuffer[1024];
int i;
for(i=0;(i //MAXClient是服务器可响应连接的最大数目
{}
if(i==MAXClient) return 0L;
iBufferLength = iRemainSpace = sizeof(chInBuffer);
iEnd = 0;
iRemainSpace -= iEnd;
iBytesRead = recv(m_aClientSocket[i], (LPSTR)(chInBuffer+iEnd), iSpaceRemaining, NO_FLAGS); //用可控缓冲接收函数recv()来接收字符
iEnd+=iRead;
if (iBytesRead == SOCKET_ERROR)
ReportWinsockErr("recv出错!");
chInBuffer[iEnd] = ''\0'';
if (lstrlen(chInBuffer) != 0)
{PrintString(chInBuffer); //服务器端文字显示
OnServerBroadcast(chInBuffer); //自己编写的函数,向所有连接的客户广播这个客户的聊天文字
}
return(0L);
}
对于客户断开连接,会产生一个FD_CLOSE消息,只须相应地用closesocket()关闭相应的Socket即可,这个处理比较简单。
4.2客户端代码
连接到服务器:
void OnSocketConnect()
{ WSADATA wsaData;
DWORD dwIPAddr;
SOCKADDR_IN sockAddr;
if(WSAStartup(WINSOCK_VERSION,&wsaData)) //调用Windows Sockets DLL
{MessageBox("Winsock无法初始化!&qu