首页 > 解决方案 > 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();
        }

标签: javapythonsocketsserversocket

解决方案


Python 客户端的调用connection.shutdown()可能会引发错误,因为 Java 服务器已经关闭了连接,并且shutdown()不喜欢这样。

对我有用的是调用“connection.close()”而不是“connection.shutdown()”。调用关闭时我没有看到错误。


推荐阅读