Socket Send Receive 问题

vipshenji 2011-12-17 11:43:20
CSocket Send代码:

UpdateData();//从编辑框获取数据m_str
int ilen = m_str.GetLength();
int nLen = m_socketCon.Send(m_strMsg,iLen);
if(nLen != SOCKET_ERROR)
{
//Do some UI Work
}


CSocket Receive代码
TCHAR buff[4096];
int nRead;
nRead = m_socketCon.Receive(buff, 4096);
if(nRead != SOCKET_ERROR)
{
buff[nRead] = NULL; //terminate the string
CString strTemp(buff);
// DO SOME UI Work
}

想问为什么环境在Use Multi-Byte Character Set下就能正确接收,但是在Use Unicode Character Set下会出现接收不正确情况。想问下此时应该怎么接收
...全文
76 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
战在春秋 2011-12-18
  • 打赏
  • 举报
回复
二种字符集对TCHAR的解释不同:
For ANSI and DBCS platforms, TCHAR is defined as follows:
typedef char TCHAR;


For Unicode platforms, TCHAR is defined as synonymous with the WCHAR type.
vipshenji 2011-12-18
  • 打赏
  • 举报
回复
谢谢 我改了下 对了
在发送的情况下
m_socketCon.Send(m_strMsg,m_strMsg.GetLength() * sizeof(TCHAR));
在接收的情况下
TCHAR buff[4096];
int nRead;
nRead = m_socketCon.Receive(buff, 4096);
if(nRead != SOCKET_ERROR)
{
buff[nRead/sizeof(TCHAR)] = NULL; //terminate the string
CString strTemp(buff);
}




[Quote=引用 1 楼 sinservice 的回复:]
int nLen = m_socketCon.Send(m_strMsg,iLen);

以及 接收方的

buff[nRead] = NULL; //terminate the string

有问题。

你改变项目的字符设定,导致条件编译TCHAR的生成是不一样的。在第1句里,记住,写流(磁盘文件、套接字、等等)的单位永远是字节,而你得到的iLen是字符数,不是字节数,你应该用……
[/Quote]
vipshenji 2011-12-18
  • 打赏
  • 举报
回复
看了下 CString::GetLength()在ASCII码下返回的事情 字节数
但是在Unicode则实际上返回的是字符数而不是字节数
「已注销」 2011-12-18
  • 打赏
  • 举报
回复
int nLen = m_socketCon.Send(m_strMsg,iLen);

以及 接收方的

buff[nRead] = NULL; //terminate the string

有问题。

你改变项目的字符设定,导致条件编译TCHAR的生成是不一样的。在第1句里,记住,写流(磁盘文件、套接字、等等)的单位永远是字节,而你得到的iLen是字符数,不是字节数,你应该用iLen乘以sizeof(TCHAR)即可得到字节数。

第2句的错误也是如此,你得到nRead是字节数,不是字符数。

之所以你用“Use Multi-Byte Character Set”设置可以正确运行,是因为sizeof(TCHAR)为1,1乘以任何数都等于那个数,而你改变设置后,则不为1了。


18,356

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 网络编程
c++c语言开发语言 技术论坛(原bbs)
社区管理员
  • 网络编程
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧