BOOL CChatSrvDlg::InitSocket()
{
m_socket=socket(AF_INET,SOCK_DGRAM,0);
if(m_socket==INVALID_SOCKET)
{
MessageBox("套接字创建失败!");
return FALSE;
}
}
void CChatSrvDlg::OnBulidServer()
{
// TODO: Add your control notification handler code here
InitSocket();
SOCKADDR_IN addrsrv;
addrsrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
addrsrv.sin_family=AF_INET;
addrsrv.sin_port=htons(6000);
int retval;
retval=bind(m_socket,(SOCKADDR*)&addrsrv,sizeof(SOCKADDR));
if(retval==SOCKET_ERROR)
{
closesocket(m_socket);
MessageBox("套接字绑定失败!");
}
m_ilen=sizeof(SOCKADDR);
char recvbuf[100];
char tempbuf[200];
while(TRUE)
{
//等待接受数据
recvfrom(m_socket,recvbuf,strlen(recvbuf)+1,0,(SOCKADDR*)&m_addrclient,&m_ilen);
sprintf(tempbuf,"%s",recvbuf);
SetDlgItemText(IDC_EDIT_SRV,tempbuf);
if(IDC_SENDTO)
{
OnSendto();
}
if(IDC_FINISH_SRV)
{
OnFinishSrv();
break;
}
}
}
void CChatSrvDlg::OnSendto()
{
// TODO: Add your control notification handler code here
CString strsend;
GetDlgItemText(IDC_SEND_DATA,strsend);
SetDlgItemText(IDC_EDIT_SRV,strsend);
char sendbuf[100];
//发送数据
GetDlgItemText(IDC_SEND_DATA,(CString)sendbuf);
sendto(m_socket,sendbuf,strlen(sendbuf)+1,0,(SOCKADDR*)&m_addrclient,m_ilen);
}
void CChatSrvDlg::OnFinishSrv()
{
// TODO: Add your control notification handler code here
SOCKADDR_IN addrclient;
int len=sizeof(SOCKADDR);
sendto(m_socket,"聊天结束",strlen("聊天结束")+1,0,(SOCKADDR*)&addrclient,len);
MessageBox("聊天结束!");
closesocket(m_socket);
WSACleanup();
}
以上代码是我在做一个基于套接字的网络聊天程序中服务器端的部分代码,编译可通过,但建立服务器时就会出现套接字绑定失败!
如果那位大侠愿意慷慨帮助,留下邮箱,我把原文件全发过去!