Unable to read beyond the end of the stream

0

I was trying to create a sockets connection between Java and C #, 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.

Excerpt from the C # code that reads:

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

Complete C # code: link

The Java code that is sending the message through the socket is as follows:

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: link

    
asked by anonymous 11.05.2014 / 16:28

1 answer

3

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 the line feed (0x0A or 0x0D).

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

If you want to use println to write the string from the java side, consider reading the bytes in the receiver until you find the end of the line (0x0A / 0x0D). An alternative is to use StreamReader and method ReadToEnd() 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);
    
12.05.2014 / 06:03