开启服务器功能:
void OnServerOpen() //开启服务器功能
{
WSADATA wsaData
int iErrorCode
char chInfo[64]
if (WSAStartup(WINSOCK_VERSION, &wsaData)) //调用Windows Sockets DLL
{ MessageBeep(MB_ICONSTOP)
MessageBox("Winsock无法初始化!", 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无法初始化!",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设定失败!")
}
接收服务器端发送的字符也使用可控缓冲接收函数recv(),客户端聊天的字符发送使用数据可控缓冲发送函数send(),这两个过程比较简单,在此就不加赘述了。
这是一个采用winapi编写的socket网络聊天通讯程序,该段代码为服务器端,使用udp通讯协议#include <Winsock2.h>
#include <stdio.h>
void main()
{
WORD wVersionRequested
WSADATA wsaData
int err
wVersionRequested = MAKEWORD( 1, 1 )
//初始化winsocket
err = WSAStartup( wVersionRequested, &wsaData )
if ( err != 0 ) {
return
}
如果本地windows系统地socket库版本号不是1.1,则退出
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
WSACleanup( )
return
}
//创建socket服务,使用udp协议
SOCKET sockClient=socket(AF_INET,SOCK_DGRAM,0)
SOCKADDR_IN addrSrv
//本地服务地址为192.168.1.107,端口号为6000
addrSrv.sin_addr.S_un.S_addr=inet_addr("192.168.1.107")
addrSrv.sin_family=AF_INET
addrSrv.sin_port=htons(6000)
char recvBuf[100]//接收数据包
char sendBuf[100]//发送数据包
char tempBuf[200]//临时存储区
int len=sizeof(SOCKADDR)
while(1)
{
printf("Please input data:\n")
//用户输入一串字符串
gets(sendBuf)
//向客户端提交字符串数据包
sendto(sockClient,sendBuf,strlen(sendBuf)+1,0,
(SOCKADDR*)&addrSrv,len)
//从客棚信户端接收应答纤和信消息
recvfrom(sockClient,recvBuf,100,0,(SOCKADDR*)&addrSrv,&len)
//如果接收的应答字符串首位字符为“q”,则告知对方对话结束
if('q'==recvBuf[0])
{
sendto(sockClient,"q",strlen("q")+1,0,
(SOCKADDR*)&addrSrv,len)
printf("Chat end!\n")
break
}
//打印出对方毁轮聊天的ip和聊天内容
sprintf(tempBuf,"%s say : %s",inet_ntoa(addrSrv.sin_addr),recvBuf)
printf("%s\n",tempBuf)
}
//关闭socket服务
closesocket(sockClient)
WSACleanup()
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)