异步UDP聊天器

BOOL CChat_AsycDlg::InitSocket()
{
    m_socket=WSASocket(AF_INET,SOCK_DGRAM,0,NULL,0,0);
    if(INVALID_SOCKET==m_socket)
    {
        MessageBox("创建套接字失败");
        /*int nCodeError=::GetLastError();
        CString s;
        s.Format("%d",nCodeError);
        MessageBox(s,MB_OK);*/
        return FALSE;
    }
    sockaddr_in addr;
    addr.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
    addr.sin_family=AF_INET;
    addr.sin_port=htons(6000);
    
    if(SOCKET_ERROR==bind(m_socket,(SOCKADDR *)&addr,sizeof(SOCKADDR)))
    {
        MessageBox("绑定失败");
        return FALSE;
    }
    if(SOCKET_ERROR==WSAAsyncSelect(m_socket,m_hWnd,UM_SOCK,FD_READ))
    {
        MessageBox("注册网络读取事件失败");
        return FALSE;
    }
    return TRUE;
}

LRESULT CChat_AsycDlg::OnSock(WPARAM wparam,LPARAM lparam)
{
    switch (LOWORD(lparam))
    {
    case FD_READ:
        WSABUF wsaBuf;
        wsaBuf.buf=new char[200];
        wsaBuf.len=200;
        DWORD dwRead;
        DWORD dwFlag=0;
        SOCKADDR_IN addFrom;
        int len=sizeof(SOCKADDR);
        CString str;
        CString strTemp;
        HOSTENT *pHost;        
        if(SOCKET_ERROR==WSARecvFrom(m_socket,&wsaBuf,1,&dwRead,&dwFlag,
            (SOCKADDR *)&addFrom,&len,NULL,NULL))
        {
            MessageBox(_T("接收数据失败"));
            delete[] wsaBuf.buf;
            return FALSE;
        }
        pHost=gethostbyaddr((char *)&addFrom.sin_addr.S_un.S_addr,len,AF_INET);        
        //str.Format("%s 说: %s",inet_ntoa(addFrom.sin_addr),wsaBuf.buf);
        str.Format("%s 说: %s",pHost->h_name,wsaBuf.buf);
        
        str+="\r\n";
        GetDlgItemText(IDC_EDIT_RECV,strTemp);
        str+=strTemp;
        SetDlgItemText(IDC_EDIT_RECV,str);
        delete[] wsaBuf.buf;
        break;    
    }
    return TRUE;
}
void CChat_AsycDlg::OnBnClickedButtonSend()
{
    // TODO: 在此添加控件通知处理程序代码
    DWORD dwIP;
    SOCKADDR_IN addTo;
    CString strSend;
    WSABUF wsaBuf;
    DWORD dwSend;
    int len;
    CString strHostName;
    HOSTENT *pHost;
    if(GetDlgItemText(IDC_EDIT_HOSTNAME,strHostName),strHostName=="")
    {
        ((CIPAddressCtrl *)GetDlgItem(IDC_IPADDRESS1))->GetAddress(dwIP);
        addTo.sin_addr.S_un.S_addr=htonl(dwIP);
    }
    else
    {
        pHost=gethostbyname(strHostName);
        addTo.sin_addr.S_un.S_addr=*((DWORD *)pHost->h_addr_list[0]);
    }
    addTo.sin_family=AF_INET;
    addTo.sin_port=htons(6000);
    
    GetDlgItemText(IDC_EDIT_SEND,strSend);
    len=strSend.GetLength();
    wsaBuf.buf=strSend.GetBuffer(len);
    wsaBuf.len=len+1;
    SetDlgItemText(IDC_EDIT_SEND,"");
    if(SOCKET_ERROR==WSASendTo(m_socket,&wsaBuf,1,&dwSend,0,(SOCKADDR *)&addTo,sizeof(SOCKADDR),NULL,NULL))
    {
        MessageBox("发送数据失败");
        return ;
    }  

    
}


你可能感兴趣的:(网络编程)