如何在Python中两次向套接字发出请求?

时间:2018-02-14 15:10:56

标签: python file sockets websocket request

我想知道如何在套接字shutdown之后两次向套接字发出请求。

当客户端首次连接时,它将发送字符串request以从服务器请求文件。然后它将对文件执行某些操作并发回完成的结果。

即:

  1. 从服务器请求文件。
  2. 对文件执行某些操作。
  3. 发回新文件。
  4. 这是我到目前为止所得到的:

    server.py

    import socket
    import sys
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(("localhost", 3000))
    s.listen(5)
    
    while True:
        (c, addr) = s.accept()
    
        request = c.recv(1024)
    
        if(request == "request"):
            f = open("image.png", "rb")
            l = f.read(1024)
            while(l):
                c.send(l)
                l = f.read(1024)
            f.close()
            print("Done sending")
    
        elif(request == "validate"):
            # echo back request
            c.send(c.recv(1024))
    
        c.close()
    s.close()
    

    client.py

    import socket
    import sys
    
    # connect to server
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("localhost", 3000))
    
    # request file
    s.send("request")
    
    f = open("test.png", "wb")
    l = s.recv(1024)
    
    while(l):
        f.write(l)
        l = s.recv(1024)
    
    f.close()
    
    print("Done receiving")
    
    s.shutdown(socket.SHUT_WR)
    s.close()
    
    # do something with the file
    # ...
    
    # send new file back
    s.send("validate")
    s.send("Hello, World") # dummy input just to see if it's working
    
    s.close() # 's' has already been closed, but I don't know how I should make another request after 's.shutdown(...)'
    

    这就是我到目前为止所做的,所以如果它完全错了请告诉我!

1 个答案:

答案 0 :(得分:0)

连接关闭后,一旦关闭连接,您必须从客户端重新打开与服务器(仍在侦听)的连接。以下代码段演示了这一点:

<强> client.py

template <typename Needle, typename... Haystack>
bool my_check(const Needle& needle, const Haystack&... haystack)
{
    return ((needle == haystack) || ...);
}