Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x Socket server-readlines()函数导致程序停止/卡住_Python 3.x - Fatal编程技术网

Python 3.x Socket server-readlines()函数导致程序停止/卡住

Python 3.x Socket server-readlines()函数导致程序停止/卡住,python-3.x,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.liste

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

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()并在执行后停止客户端时,服务器会打印发送的完整消息,我感到困惑

我怀疑在不关闭连接的情况下,
readlines()
不知道何时停止读取。不过,这只是一个猜测。谢谢你的评论,我对此感到非常困惑,
readlines()
输出了一个列表,所以我不明白为什么要卡住程序。我怀疑如果不关闭连接,
readlines()
就不知道什么时候停止阅读。不过,这只是一个猜测。谢谢你的评论,我对此感到非常困惑,
readlines()
输出一个列表,所以我不明白为什么要卡住程序