发送端:
int len = m_strSend.GetLength();
if (0 == len)
{
strState.Format(L"请填写需要发送的数据!");
GetDlgItem(IDC_STATIC_SEND_STATE)->SetWindowText(strState); //动态指定static text显示内容
return;
}
int byteLenSend = (len + 1)*sizeof(wchar_t);
USES_CONVERSION;//字符编码转换所需要的宏定义
int sendLen = SndData(W2A(m_strSend), byteLenSend);
if (byteLenSend == sendLen)
{
m_strReceived.SetWindowText(m_strSend);
GetDlgItem(IDC_EDIT_SEND)->SetWindowText(L"");
}
接收端:
char tempSocketReceive[MAXDATALENGTH] = "";
memset(tempSocketReceive, 0, MAXDATALENGTH);//char清空;
tempSocketReceive[MAXDATALENGTH - 1] = ‘\0‘;//防止数据末尾出现烫烫烫烫,加上之后仍然出现
int length = recvfrom(listen_socket, tempSocketReceive, MAXDATALENGTH, 0, (struct sockaddr *)&addr, &addr_len);
//判断为将多字节编码转化为宽字节编码所需要的内存空间
DWORD dwNum = MultiByteToWideChar(CP_ACP, 0, tempSocketReceive, -1, NULL, 0);
//在堆上分配内存,申请的内存必要要释放,不然早晚会内存泄露导致程序崩溃
wchar_t *pwText;
pwText = new wchar_t[dwNum];
//将对字节转换位宽字皆unicode,转换结果保存在堆内存上,记得delete
MultiByteToWideChar(CP_ACP, 0, tempSocketReceive, -1, pwText, dwNum);
//将收到的数据用CString表示,便于在MFC上显示和用CFile写入文件
CString rawData(pwText);//未经解析的原始串口数据数据
delete[]pwText;