gpt4 book ai didi

java - Python 客户端 Java 服务器 服务器接收到 null

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:00:49 26 4
gpt4 key购买 nike

顾名思义,客户端向服务器发送空值。我想不通为什么

Python 客户端

import socket

HOST = "localhost"
PORT = 5000

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))

dict = {
0: "doug",
1: "korg",
2: "stefan",

}
for x in range(0, 3):
if x == 3:
sock.sendall("Bye\n")
print(sock.recv(1024))
sock.sendall(b"{}\n".format(dict.get(x)))
print(dict.get(x))
print(sock.recv(1024))

Java 服务器:

    public void run() {
String fromClient;
String toClient;
try {
ServerSocket server = new ServerSocket(5000);
System.out.println("wait for connection on port 5000");

boolean run = true;
Socket client = server.accept();

BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true);


while (run) {
System.out.println("got connection on port 5000");
fromClient = in.readLine();
System.out.println("received: " + fromClient);


if (fromClient.equals("Bye")) {
toClient = "Aight later man";
System.out.println("send eyB");
out.println(toClient);
client.close();
System.out.println("socket closed");
break;
}
out.println("cool next User Please");
}
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
}
}

当前 3 个字符串从客户端发送到服务器并且服务器响应时,当发送 Bye 时,服务器接收到 null 并抛出 nullpointerexception。

我的代码基于这篇文章。 Communication between python client and java server

问题存在于 String as ByteString 形式。

服务器输出:

wait for connection on port 5000
got connection on port 5000
received: doug
got connection on port 5000
received: korg
got connection on port 5000
received: stefan
got connection on port 5000
Exception in thread "Thread-0" java.lang.NullPointerException
at Jserver.run(Jserver.java:28)
received: null

Process finished with exit code 0

客户端输出:

doug
cool next User Please

korg
cool next User Please

stefan
cool next User Please

最佳答案

您的问题是由 python 代码引起的,它从不发送“再见”命令。

python代码中的错误:

您的 python 代码从 0(含)循环到 3(不含),因为 3 被排除在外,代码永远不会进入“再见” block ,也永远不会发送它。 (打印 x 以确认这一点)

在循环之后放置“bye”代码。

for x in range(0, 3):
sock.sendall(b"{}\n".format(dict.get(x)))
print(dict.get(x))
print(sock.recv(1024))
sock.sendall("Bye\n")
print(sock.recv(1024))

Java代码中的错误

是的,Java 代码中也有一个错误,主要是它没有正确处理流关闭。

当 Python 程序在代码末尾关闭时,Java 程序将收到一个干净的退出,这是一种无异常的关闭套接字的方式,并将导致 readLine返回空值。

此 null 然后导致以下异常:

Exception in thread "Thread-0" java.lang.NullPointerException

由于看到 null 值意味着套接字已关闭,您还可以将其作为适当的“再见”响应或作为错误条件进行线程处理。

            if (fromClient == null || fromClient.equals("Bye")) {

关于java - Python 客户端 Java 服务器 服务器接收到 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53042610/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com