Alessandro Alessandro - 2 months ago 9
Android Question

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

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);

Answer

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.

Comments