0

我正在为第三方 Java 客户端制作 Python 服务器。客户端使用DataInputStream.readUTF(),我想知道如何通过 Java 的套接字在 Python 中编写 UTF。

服务器当前代码:

import socket
port = 3687

def main():
    print("Running on port " + str(port))
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(("", port))
    s.listen(1)
    c, a = s.accept()
    c.send(str(unichr(1))) #Packet id
    c.send("Hello".encode('utf-8')) #MOTD
    c.send(str(unichr(0)) + str(unichr(3))) #Players
    c.close()
    s.close()
    print("Complete")

main()

客户端代码(不能更改):

Socket s = new Socket();
s.setKeepAlive(false);
s.setSoTimeout(3000);
s.connect(new InetSocketAddress(address,port), 3000);
s.getOutputStream().write(0);
DataInputStream in = new DataInputStream(s.getInputStream());
if(in.read() != 1)
    throw new Exception("Invalid response");
serverMOTD = in.readUTF());
playersOnline = in.readChar();
s.close();

客户端在读取 UTF 时崩溃,并出现以下错误:

java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:168)
    at java.io.DataInputStream.readFully(DataInputStream.java:178)
    at java.io.DataInputStream.readUTF(DataInputStream.java:592)
    at java.io.DataInputStream.readUTF(DataInputStream.java:547)
4

0 回答 0