Unable to read beyond the end of the stream

Was trying to create a sockets connection between Java and C#, with Java being the client and C# the server.

But when I use BinaryReader to read the data, it returns an error:

Unable to read beyond the end of the stream.

Snippet of C# code that does the Reading:

Console.WriteLine("Iniciando...");
IPEndPoint ipp = new IPEndPoint(IPAddress.Parse("192.168.173.1"), 5000);
tccp=new TcpListener(ipp);
tccp.Start();
Console.WriteLine("Conexão TCP iniciada, ip : 127.0.0.1, porta: 4567");

doidaco = tccp.AcceptSocket();
newton = new NetworkStream(doidaco);
rr = new BinaryReader(newton);

string mensagem="";
do{
     mensagem = rr.ReadString();
    Console.WriteLine("\nMensagem do cliente: "+mensagem);

}while(doidaco.Connected);

Full C # code: http://pastebin.com/m2Vpznts

The Java code that is sending the message through the socket is the next:

public static void main(String[] args) throws IOException {
    socket = new Socket("192.168.173.1", 5000);
    Scanner sca = new Scanner(socket.getInputStream());
    PrintWriter ee = new PrintWriter(socket.getOutputStream());
    ee.println("Hello!");
    System.out.println("Mensagem enviada.");
    ee.close();
    System.out.println("Conexão encerrada.");
    sca.close();
    socket.close();
}

Java code: http://pastebin.com/2ewZtxVk

Author: carlosfigueira, 2014-05-11

1 answers

Your problem is that the format of the message written in the socket (java code) is different from the format expected in the reader (C#code). The call to ee.println("Hello!"); will write the bytes relative to the string " Hello!"(0x48 0x65 0x6C 0x6C 0x6F 0x21) followed by line feed (0x0A or 0x0D).

The call to BinaryReader.ReadString, however, expects the first byte of the message to indicate the size of the string (see MSDN documentation for this method). So when BinaryReader begins to reading the string, it sees the" size " of 0x48 and tries to read more 0x48 (72) bytes from the stream - and there is no such amount of bytes, which is why you get the error you mentioned.

If you want to use println to write the string on the java side, consider reading the bytes on the receiver until you find the end of the line (0x0A / 0x0D). An alternative is to use a StreamReader and the ReadToEnd() method to read everything the client sent.

var clientSocket = tccp.AcceptSocket();
var clientSocketStream = new NetworkStream(clientSocket);
var streamReader = new StreamReader(clientSocketStream);

string mensagem = streamReader.ReadToEnd();
Console.WriteLine("Mensagem do cliente: " + mensagem);
 3
Author: carlosfigueira, 2014-05-12 23:12:42