2019年6月3日 星期一

c#丟中文字到wxSocket Server變亂碼!?

wxWidget架構事實上是很好用了,wxSocket也包很好,
不過從c# client connect wxSocket Server收到後,卻變成了亂碼
(在已經中文化zh_TW.UTF-8的pi3 linux之下)....
-----c# socket client---------------
               IPAddress ipAddress = System.Net.IPAddress.Parse("wxSocketsServer所在的IP");
                IPEndPoint remoteIP = new IPEndPoint(ipAddress, 3000);

                // Create a TCP/IP  socket.
                Socket sender = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream, ProtocolType.Tcp);
                sender.SendTimeout = 60000;
                try {
                    sender.Connect(remoteIP);
                    string msg2Send ="中文測試";
                    byte[] msg =  Encoding.ASCII.GetBytes(msg2Send);
                    // Send the data through the socket.
                    int bytesSent = sender.Send(msg);
                    byte[] bytes = new byte[1024];
                    int bytesRec = sender.Receive(bytes);
                    string returnMsg = Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    // Release the socket.
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                } catch (Exception expConn) {
                      ExceptionLog.log(expConn, expConn.Message);
                 
                }

------------------------------------
-------wxSoekct Server--------
void MyFrame::OnSocketEvent(wxSocketEvent& event)
{
wxSocketBase *sock = event.GetSocket();
// Process the event
switch(event.GetSocketEvent())
{
case wxSOCKET_INPUT:
{
char buf[10];
// Read the data
sock->Read(buf, sizeof(buf));
// Write back a OK msg to client
                      std::string msgOK("SOCKET RCV OK");
                     sock->Write(msgOK.c_str(),msgOK.length());  // We are done with the socket, destroy it
sock->Destroy();
break;
}
case wxSOCKET_LOST:
{
sock->Destroy();
break;
}
    }
}
---------------------------
結果在wxSocket的socket read buf出現中文亂碼!!好像很難解決的樣子說....


Take easy 啦,不必想太多上面的c# client改一下
byte[] msg =  Encoding.ASCII.GetBytes(msg2Send); 
改為
byte[] msg =  System.Text.Encoding.GetEncoding("utf-8").GetBytes(msg2Send);
wxSocket server read到buffer的資料就會是正確的中文了
不用base64啦,就是這麼簡單
大家加油吧

沒有留言:

張貼留言