void OnServerOpen() //开启服务器功能
{
WSADATA wsaData;
int iErrorCode;
char chInfo[64];
if (WSAStartup(WINSOCK_VERSION, &wsaData)) //调用Windows Sockets DLL
{ MessageBeep(MB_ICONSTOP);
MessageBox("Winsock无法初始化!", AfxGetAppName(), MB_OKMB_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;
}
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);
}
void OnSocketConnect()
{ WSADATA wsaData;
DWord dwIPAddr;
SOCKADDR_IN sockAddr;
if(WSAStartup(WINSOCK_VERSION,&wsaData)) //调用Windows Sockets DLL
{MessageBox("Winsock无法初始化!",NULL,MB_OK);
return;
}
m_hSocket=socket(PF_INET,SOCK_STREAM,0); //创建面向连接的socket
sockAddr.sin_family=AF_INET; //使用TCP/IP协议
sockAddr.sin_port=m_iPort; //客户端指定的IP地址
sockAddr.sin_addr.S_un.S_addr=dwIPAddr;
int nConnect=connect(m_hSocket,(LPSOCKADDR)&sockAddr,sizeof(sockAddr)); //请求连接
if(nConnect)
ReportWinsockErr("连接失败!");
else
MessageBox("连接成功!",NULL,MB_OK);
int iErrorCode=WSAAsyncSelect(m_hSocket,m_hWnd,WM_SOCKET_READ,FD_READ);
//指定响应的事件,为服务器发送来字符
if(iErrorCode==SOCKET_ERROR)
MessageBox("WSAAsyncSelect设定失败!");
}
新闻热点
疑难解答