java - python socket - [Errno 57] 尽管响应良好,但未连接套接字
问题描述
我用 Java 构建了一个简单的服务器套接字,并使用 python 客户端套接字与之通信。认为响应很好,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)
我的服务器套接字(在 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();
}
解决方案
Python 客户端的调用connection.shutdown()
可能会引发错误,因为 Java 服务器已经关闭了连接,并且shutdown()
不喜欢这样。
对我有用的是调用“connection.close()”而不是“connection.shutdown()”。调用关闭时我没有看到错误。
推荐阅读
- python-3.x - 为什么用 Process 调用多处理模块可以创建相同的实例?
- python - 删除新的换行符,但仅在引号之间
- flutter - 使用手势检测器,但接收预期类型为“地图”的值
',但得到了“空”类型之一 - powershell - 如何在 PowerShell 中关闭安装完成对话框?
- arrays - 为什么最终数组返回最后一个数组的 7 行编译而不是 Google Apps 脚本中的 7 个唯一数组值?
- javascript - 在 FullCalendar 月时间线视图中显示多年?
- java - 如何在没有getProtectionDomain的Android应用程序中获取Kotlin中当前类文件的路径
- python - 如何对csv文件中的列进行排序?
- javascript - 如何删除两个单词之间的所有空格?
- r - 在 Windows 10 下安装“ReporteRs”和“ReporteRsjars”时出错