java pythonsocket[Errno 57]socket未连接,尽管响应良好
我用Java构建了一个简单的服务器socket,并使用python客户端socket与之通信。虽然响应很好,但是connection.shutdown(socket.SHUT_RDWR)
总是失败,并出现错误[Errno 57] Socket is not connected
。由于客户端可以从服务器获得响应,我认为socket已经连接。但是为什么它总是说插座没有连接呢?我非常困惑。有什么想法吗?非常感谢
我的客户(在Python3中):
url = '/import_image'
headers = [
b"PUT " + bytes(url, "UTF-8") + b" HTTP/1.0",
b'Content-Type: application/octet-stream',
b"Content-Length: " + bytes("hello world", "UTF-8"),
b"Connection: close",
b""
]
for h in headers:
connection.sendall(h)
connection.sendall(b"\r\n")
response = HTTPResponse(connection)
response.begin()
if response.status != 200:
raise Exception("Received HTTP response {0}: {1}".format(response.status, response.reason))
else:
print(response.read())
try:
# This will fail with the error: [Errno 57] Socket is not connected
connection.shutdown(socket.SHUT_RDWR)
except Exception as e:
print(e)
我的服务器socket(在Java8中):
ServerSocket serverSocket = new ServerSocket(Defs.SOCKET_SERVER_PORT); // port 8888
try {
while (true) {
log.info("Waiting for connection on port " + Defs.SOCKET_SERVER_PORT);
Socket socket = serverSocket.accept();
log.info("Connection received. Handling request...");
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
new BufferedOutputStream(socket.getOutputStream()), "UTF-8"));
String header = "HTTP/1.0 200 OK\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: ";
String output = "<html><head><title>Example</title></head><body><p>success!</p></body></html>";
out.write(header + output.length() + "\r\n\r\n" + output);
out.flush();
out.close();
}
} finally {
serverSocket.close();
}
# 1 楼答案
Python客户端对
connection.shutdown()
的调用可能会抛出错误,因为Java服务器已经关闭了连接,shutdown()
不喜欢这样对我来说,有效的方法是称之为“连接”。关闭()而不是“连接”。shutdown()。我在调用close时没有看到错误