MINA服務端與C++用戶端通訊(2)

來源:互聯網
上載者:User

Java與C++通訊還有編碼轉碼的問題存在,假設通訊編碼採用UTF-8

C++用戶端發送時需要轉碼成UTF-8編碼,接收服務端應答訊息後再轉回Unicode或者GBK編碼

下面給出完成的C++用戶端通訊樣本:

void Transcoding(LPCTSTR src, UINT srcCode, string& dest, UINT destCode) { int len = MultiByteToWideChar(srcCode, 0, src, -1, NULL, 0);   WCHAR* srcTemp = new WCHAR[len];   MultiByteToWideChar(srcCode, 0, src, -1, srcTemp, len);   len = WideCharToMultiByte(destCode, 0, srcTemp, -1, NULL, 0, NULL, NULL);   char* destTemp = new char[len];   WideCharToMultiByte(destCode, 0, srcTemp, -1, destTemp, len, NULL, NULL);   dest = destTemp; delete []srcTemp;   delete []destTemp;   }int _tmain(int argc, _TCHAR* argv[]){// client connectCXSocket client;client.initWinSocket();client.setAddress("127.0.0.1");client.setPort(1234);client.setProtoType(TCP);int ret = client.connect();if(ret < 0){getchar();return 0;}// 加通訊協議頭demo// client sendchar send[] = {"CXSocket 第一個測試案例."};string utf8;Transcoding(send, CP_ACP, utf8, CP_UTF8);XNET::TPacketHeader sendHeader;sendHeader.m_HeaderSig = 0xABCD;swap_2(sendHeader.m_HeaderSig);sendHeader.m_Length = (int)utf8.length();swap_4(sendHeader.m_Length);char buffer[1024] = {0};memcpy(buffer, &sendHeader, XNET::TCP_HEADLEN);memcpy(&buffer[XNET::TCP_HEADLEN], utf8.c_str(), utf8.length());client.sendBuf(buffer, (int)(XNET::TCP_HEADLEN + utf8.length()));// client recvXNET::TPacketHeader recvHeader;client.receiveBuf(&recvHeader, XNET::TCP_HEADLEN);swap_2(recvHeader.m_HeaderSig);swap_4(recvHeader.m_Length);char* recv = new char[recvHeader.m_Length + 1];memset(recv, 0, recvHeader.m_Length + 1);client.receiveBuf(recv, recvHeader.m_Length);string ansi;Transcoding(recv, CP_UTF8, ansi, CP_ACP);client.close();client.uninitWinSocket();getchar();return 0;}

CXSocket類:http://code.google.com/p/x-net/

MINA服務端:http://download.csdn.net/source/3418326

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.