套接字服务器-readlines()函数导致我的程序停止/卡住

时间:2019-06-17 13:38:23

标签: python-3.x

我正在尝试创建一个简单的套接字服务器的示例,我需要从客户端接收多行数据,因此这是套接字服务器的代码:

import socket
import sys

host = 'localhost'
port = 5006

c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
c.bind((host, port))
c.listen(1)

while True:
    try:
        print("1")
        csock, caddr = c.accept()
        print("2")
        with csock.makefile('rw', 2**16) as cfile:
            print("3")
            print(cfile.readline()) // When I use readline, it goes ok, but only get the first line, I need every line from data sent by client
            print("4")
            cfile.close()
            print("5")
        print("5.5")
        csock.sendall("OK".encode('UTF-8'))
        print("6")
        csock.close()
        print("7")
    except KeyboardInterrupt:
        print("Keyboard exit")
        if 'csock' in locals():
            csock.close()
        sys.exit()
    except Exception as e:
        print(e)

现在,当我使用readlines()时,我的程序就停滞了,在print("3")之后什么也不做 我也尝试过使用read(),但是仍然卡住,继续等待客户端和服务器

这是我用于客户端的代码:

import socket

def query(host, port):
    msg = \
        'MSH|^~\&|REC APP|REC FAC|SEND APP|SEND FAC|20110708163513||QBP^Q22^QBP_Q21|111069|D|2.5|||||ITA||EN\r' \
        'QPD|IHE PDQ Query|111069|@PID.5.2^SMITH||||\r' \
        'RCP|I|'

    # establish the connection
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect((host, port))
        # send the message
        sock.sendall(msg.encode('UTF-8'))
        # receive the answer
        received = sock.recv(1024*1024)
        return received
    finally:
        sock.close()


if __name__ == '__main__':
    res = query('localhost', 5006)
    print("Received response: ")
    print(repr(res))

当我使用readlines()并在执行后停止客户端时,服务器会打印已发送的完整消息,我很困惑

0 个答案:

没有答案