我用Java构建了一个简单的服务器套接字,并使用python客户端套接字与之通信。认为响应良好,因此connection.shutdown(socket.SHUT_RDWR)
总是失败,并显示错误[Errno 57] Socket is not connected
。由于客户端可以从服务器获取响应,因此我认为套接字已经连接。但是为什么经常说插座未连接呢?我很困惑。有任何想法吗?非常感谢!
我的客户端(在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)
我的服务器套接字(在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();
}
答案 0 :(得分:0)
Python客户端对connection.shutdown()
的调用很可能引发错误,因为Java服务器已经关闭了连接,而shutdown()
对此并不满意。
对我有用的是调用“ connection.close()”而不是“ connection.shutdown()”。调用close时没有看到错误。