I’m having trouble getting a socket connection between Android(client) and a c# app(server) to read a response correctly.
I’ve successfully got a message sending from android to c#, and I’m reading it fine on that end. But when I try to send an acknowledgement back to android, I don’t know the correct way to handle this, and I’ve had to make some assumptions where tutorials have been unclear. I am getting a response back in android, but it’s not 100% correct. I’ve verified via Wireshark that c# is sending what I want it to send, and the text looks fine until it gets to android.
C#:
public void SendClientMessage()
{
NetworkStream clientStream = _Client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("Hello Client!"); //Static test message
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
…
Android:
private void listenResponse()
{
Log.i(TAG, "listenRespose() Listening...");
try
{
InputStream is = socket.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int countBytesRead = bis.read(buffer, 0, 8);
String response = new String(buffer);
Log.i(TAG, "listenResponse() Heard: " + response);
}
catch (IOException e)
{
Log.e(TAG, "listenResponse() IOException", e);
e.printStackTrace();
}
Log.i(TAG, "listenResponse() Done Listening.");
}
…
WireShark shows:
Hello Client!
…
Android LogCat shows:
listenRespose() Listening...
listenResponse() Heard: Hello Cl??????????????????????????? [... ?s continue for a long time]
listenResponse() Done Listening.
If instead I initialize my String like this:
String response = new String(buffer, 0, countBytesRead);
I don’t get all the question marks at least, but I still don’t get the full string I should be getting. Am I initializing my byte[] wrong, or is there a different way to do this better suited for plain text?
You only read 8 bytes here
instead, read all you can:
The question marks you see are because your buffer is not initialized.