TCP Server gets ???????? instead of the real message

烈酒焚心 提交于 2019-12-12 02:34:35

问题


The server is written in c# and works correctly with a client I made in c#, now i'm trying to make an android client but the server doesn't get the real message, it gets just a lot of question marks.

Here is the server

TcpListener listen = new TcpListener(IPAddress.Any, 1200);
TcpClient client;
listen.Start();
client = listen.AcceptTcpClient();
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
int data = stream.Read(buffer, 0, client.ReceiveBufferSize);
string message = Encoding.Unicode.GetString(buffer, 0, data);
Console.WriteLine(message);

this is the Android client

EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString()
PrintWriter out = new PrintWriter(new BufferedWriter(
            new OutputStreamWriter(socket.getOutputStream())),
                true);
out.println(str);

For example if I send the message "Hello", the server prints "???????????" and it happens the same for any message I send, even just 1 letter

I also tried with different methods like this one but the result is the same:

DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        out.writeBytes(str);

回答1:


Change:

string message = Encoding.Unicode.GetString(buffer, 0, data);

into:

string message = Encoding.UTF8.GetString(buffer, 0, data);

Try also UTF16. I think java uses this encoding now.



来源:https://stackoverflow.com/questions/39393788/tcp-server-gets-instead-of-the-real-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!