编写个网络聊天的程序,sendto和recvfrom函数中使用char,使用sprintf格式化呢又提示警告,要用format函数,使用CString对象呢经过lParam参数传递后又不好转换,接收端接收到的全是乱码,不知道该如何处理了,代码如下:
这是接收端的代码
这是发送端的
这是接收端的代码
DWORD WINAPI CSX15_CHATDlg::ChatProc(LPVOID lpParam)
{
SOCKET sock = ((RecvParam*)lpParam)->sock ;
HWND hWnd = ((RecvParam*)lpParam)->hWnd ;
SOCKADDR_IN AddrFrom;
int len = sizeof( SOCKADDR );
char recvBuf[200],recvTemp[400];
while(1)
{
if( SOCKET_ERROR == recvfrom(sock,recvBuf,200,0,(SOCKADDR*)&AddrFrom,&len))
{
break;
}
sprintf(recvTemp,"%s:\n%s",inet_ntoa(AddrFrom.sin_addr ),recvBuf);
::PostMessageW(hWnd,WM_RECVDATA,0,(LPARAM)recvTemp); //自定义消息,用OnRecvdata处理
}
return 0;
}
这是发送端的
afx_msg LRESULT CSX15_CHATDlg::OnRecvdata(WPARAM wParam, LPARAM lParam)
{
CString str,strtemp;
str = (char*)lParam;
GetDlgItemText( IDC_EDIT_RECV,strtemp );
strtemp += _T("\r\n");
strtemp += str;
SetDlgItemText( IDC_EDIT_RECV,strtemp );
return 0;
}
void CSX15_CHATDlg::OnBnClickedBtnSend() //发送按钮
{
// TODO: 在此添加控件通知处理程序代码
DWORD dwIP;
((CIPAddressCtrl*)GetDlgItem(IDC_IPADDRESS1))->GetAddress ( dwIP );
SOCKET socketClient = socket(AF_INET,SOCK_DGRAM,0);
SOCKADDR_IN addrTo;
addrTo.sin_addr .S_un .S_addr = htonl(dwIP);
addrTo.sin_family = AF_INET;
addrTo.sin_port = htons(6000);
CString sendBuf;
GetDlgItemText( IDC_EDIT_SEND,sendBuf );
sendto(m_socket,(const char*)&sendBuf,sendBuf.GetLength () + 1,0,(SOCKADDR*)&addrTo,sizeof( SOCKADDR));
SetDlgItemText(IDC_EDIT_SEND,_T(""));
}