2020年12月21日星期一

C# to Java UTF8 string over TCP

I'm unable to send a UTF-8 string from a C# server to a Java client due to an EOF error in the client. How do I properly configure the C# server? I assume the error lies there because this client works with the Java server shown below.

Java client's receive function does this (this also works if I receive from a Java server, shown below):

DataInputStream dataInputStream = new DataInputStream(socket.getInputStream()); //The constructor initialises a field, using the socket object.          StringBuilder inputMessage = new StringBuilder();  inputMessage.append((String) dataInputStream.readUTF());  

Desired C# server:

        static async Task Main(string[] args)          {              TcpListener server = new TcpListener(IPAddress.Any, 34567);              server.Start();              byte[] bytes = new byte[4096];              byte[] responseBytes;              using (var client = await server.AcceptTcpClientAsync()){                  using(var tcpStream = client.GetStream())                  {                      await tcpStream.ReadAsync(bytes, 0, bytes.Length);                      var playerNumber = Encoding.UTF8.GetString(bytes);                      Console.WriteLine("Player " + playerNumber + " connected."); //java client to server works.                        StringBuilder outputMessage = new StringBuilder("Some output");                      responseBytes = Encoding.UTF8.GetBytes(outputMessage.ToString());                      await tcpStream.WriteAsync(responseBytes, 0, responseBytes.Length); //This doesn't work...                  }                  server.Stop();              }          }  

The error:

java.io.EOFException      at java.base/java.io.DataInputStream.readFully(DataInputStream.java:201)      at java.base/java.io.DataInputStream.readUTF(DataInputStream.java:613)      at java.base/java.io.DataInputStream.readUTF(DataInputStream.java:568)      at Client.Connection.Receive(Connection.java:26)      at Client.Main.lambda$main$0(Main.java:30)      at com.sun.javafx.application.PlatformImpl.lambda$startup$5(PlatformImpl.java:271)      at com.sun.glass.ui.Application.invokeAndWait(Application.java:464)      at com.sun.javafx.tk.quantum.QuantumToolkit.runToolkit(QuantumToolkit.java:366)      at com.sun.javafx.tk.quantum.QuantumToolkit.lambda$startup$10(QuantumToolkit.java:280)      at com.sun.glass.ui.Application.lambda$run$1(Application.java:153)  

Interestingly, a Java server doing this works:

            DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());              StringBuilder outputMessage = new StringBuilder("Some output");              dataOutputStream.writeUTF(outputMessage.toString());              dataOutputStream.flush();  
https://stackoverflow.com/questions/65402717/c-sharp-to-java-utf8-string-over-tcp December 22, 2020 at 11:00AM

没有评论:

发表评论