tcp上的c#到java utf8字符串

u0njafvf  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(513)

我无法将utf-8字符串从c#服务器发送到java客户端,因为客户端中存在eof错误。如何正确配置c服务器?我假设错误就在那里,因为这个客户机使用下面所示的java服务器。
java客户机的receive函数可以做到这一点(如果我从java服务器接收,这也可以工作,如下所示):

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

所需的c#服务器:

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

错误:

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)

有趣的是,这样做的java服务器可以:

DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
            StringBuilder outputMessage = new StringBuilder("Some output");
            dataOutputStream.writeUTF(outputMessage.toString());
            dataOutputStream.flush();

编辑
这是从工作的java服务器接收的。“bytearr”包含我用于消息的100个字节和0的100个字节(它们位于我的消息之后)。“chararr”正确地将前100个字节视为有意义的内容,将最后200个字节视为“\u0000”:


这是从不工作的c#服务器接收的。与正确的版本相比,它似乎以两个字节开始,而且它的“chararr”仅包含数千个'\u0000':

5sxhfpxr

5sxhfpxr1#

datainputstream的readutf读取一种特殊的数据格式,它不是读取utf-8字节序列的通用方法。最值得注意的是,它需要一个指定流长度的初始字节序列。

0s0u357o

0s0u357o2#

我在这里找到了答案。将java客户机的读取方式改为以下方式:

byte[] buff = dataInputStream.readAllBytes();
String str = new String(buff, "UTF-8");

相关问题