如何使用winsock的send()函数发送宽字符? [英] How do I send wide characters using winsock's send() function?

查看:701
本文介绍了如何使用winsock的send()函数发送宽字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它说这里发送函数期望const char *。

It says here that the send function expects const char*.

如何发送宽字符?我尝试以下:

How do I send wide characters? I tried the following:

void MyClass::socksend(const wchar_t* wbuffer) {
   int i;
   char *buffer = (char *)malloc( MB_CUR_MAX );
   wctomb_s(&i,buffer, MB_CUR_MAX, (wchar_t)wbuffer);
   int buflen = strlen(buffer) + 2;
   char sendbuf[DEFAULT_BUFLEN];
   strcpy_s(sendbuf,buflen,buffer);
   sendbuf[buflen - 1] = '\n';
   int senderror = send(this->m_socket, sendbuf, buflen, 0);
   // error handling, etc goes here...

}

这不符合我的期望。它似乎没有发送任何东西到套接字。如何解决这个问题?

This doesn't do what I expect it to. It doesn't seem to be sending anything to the socket. How do I fix this?

推荐答案

首先是什么是宽字符?它是一个大于8位的整数值;这意味着你将必须处理字节序。您需要将宽字符数组编码为char数组,然后将其作为char数组发送。在接收端,您需要将char数组解码为宽字符数组。

What is a wide character in the first place? It's an integral values wider than 8-bit; this means you will have to handle Endianness. You need to encode your wide character array to a char array, and then send it as an char array. In the receiving end, you need to decode the char array to wide character array.

函数wctomb_s只编码一个宽字符 em> char数组。您要将宽字符数组编码为字符数组的函数是wcstombs_s。相应地,解码使用mbstowcs_s。

The function wctomb_s only encodes a single wide character to char array. The function you're looking to encode a wide character array to char array is wcstombs_s. Correspondingly, to decode use mbstowcs_s.

错误处理已忽略(未测试):

with error handling ommitted (untested):

void MyClass::socksend(const wchar_t* wbuffer) { 
   // determine the required buffer size
   size_t buffer_size;
   wcstombs_s(&buffer_size, NULL, 0, wbuffer, _TRUNCATE);

   // do the actual conversion
   char *buffer = (char*) malloc(buffer_size);
   wcstombs_s(&buffer_size, buffer, buffer_size, wbuffer, _TRUNCATE);

   // send the data
   size_t buffer_sent = 0;
   while (buffer_sent < buffer_size) {
       int sent_size = send(this->m_socket, buffer+buffer_sent, buffer_size-buffer_sent, 0);
       buffer_sent += sent_size;
   }

   // cleanup
   free(buffer);
}

这篇关于如何使用winsock的send()函数发送宽字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆