发送消息后关闭客户端套接字会导致错误

时间:2019-05-02 05:39:23

标签: python python-3.x sockets network-programming

我想知道为什么关闭客户端套接字会导致错误消息(如下所示)的原因

Traceback (most recent call last):
  File "client.py", line 39, in <module>
    main()
  File "client.py", line 35, in main
    accept()
  File "client.py", line 21, in accept
    len_msg = int(msg[:headersize])
ValueError: invalid literal for int() with base 10: b''

这是服务器端

import socket 
import time 
import pickle 

def connect(data, headersize = 10, looped = False):

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
        server.bind((socket.gethostname(), 1234))

        server.listen(5)

        while True:

            client_socket, address = server.accept()
            print(f"connection with {address} has been established")
            msg = pickle.dumps(data)
            msg = bytes(f"{len(msg):<{headersize}}", "utf-8") + msg 

            client_socket.send(msg)

            if looped:
                while True:
                    msg = f"{time.time()} + the new message"
                    client_socket.send(msg)


            client_socket.close()  # this causes an error

def main():
    data = {"apple":5, "pinapple":10}
    connect(data)
if __name__ == "__main__":
    main()

这是客户端

import socket
import time
import pickle 


def accept(headersize = 10):

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client:
        client.connect((socket.gethostname(), 1234))

        while True:

            new_msg = True
            full_msg = b""
            len_msg = 0
            while True:

                msg = client.recv(headersize + 4)

                if new_msg:
                    len_msg = int(msg[:headersize])
                    new_msg = False 

                full_msg += msg 
                if len(full_msg) - headersize == len_msg:

                    print(full_msg[headersize:])
                    d = pickle.loads(full_msg[headersize:])
                    print(d)
                    full_msg = b""
                    new_msg = True
def main():
    accept()

if __name__ == "__main__":
    main()

程序很简单:我只是以二进制形式将消息发送给客户端。当我在服务器端删除client_socket.close()时,没有错误-那么如何正确关闭客户端套接字?谢谢

1 个答案:

答案 0 :(得分:2)

recv在发送套接字关闭时返回b''

msg[:headersize]msg为空时返回b''

int(b'')给出了您所看到的错误。

如果套接字已关闭,则以下内容将退出客户端的内部while True:循环,因此它将不会尝试处理空消息。我看不到外部while True:的目的。

msg = client.recv(headersize + 4)
if not msg:  # empty strings are False
    break