网络服务器只向客户端发送一次数据而不是循环

Network server only sending data to client once instead of looping

如果这是一个非常愚蠢的问题,我很抱歉,我相信有人可能会在一分钟内找到答案,我最近刚接触 Python 套接字。

我希望我的服务器持续向我的客户端发送数据流,但由于某种原因,在收到第一条数据后,我的客户端就receive/print不再发送任何数据。

我的简化版server.py:

while True:
    #do some stuff with dfwebsites here
    
    senddata = True
    #time.sleep(1)
    
    #Starting the sending data part

    HEADERSIZE = 10

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((socket.gethostname(),1236))
    s.listen(5)  #queue of five
    
    while senddata==True:
        clientsocket, address = s.accept()
        print(f"Connection from {address} has been established!")

        d = pd.DataFrame(dfwebsites)
        msg = pickle.dumps(d)

        #header to specify length
        #msg = "Welcome to the server!"
        msg = bytes(f'{len(msg):<{HEADERSIZE}}','utf-8')+msg    

        clientsocket.send(msg)  #type of bytes is utf-8
        #clientsocket.close()
        senddata = False

我的client.py:

import socket
import pickle
import time

HEADERSIZE = 10

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 1236))

while True:
    full_msg = b''
    new_msg = True
    while True:
        msg = s.recv(1024)
        if new_msg:
            print("new msg len:",msg[:HEADERSIZE])
            msglen = int(msg[:HEADERSIZE])
            new_msg = False

        print(f"full message length: {msglen}")

        full_msg += msg

        print(len(full_msg))

        if len(full_msg)-HEADERSIZE == msglen:
            print("full msg recvd")
            print(full_msg[HEADERSIZE:])
            print(pickle.loads(full_msg[HEADERSIZE:]))
            new_msg = True
            full_msg = b""

为什么不能接收多个数据?

非常感谢您的帮助!我真的很喜欢评论告诉我如何改进我的问题!

要向每个客户端发送多条消息,您需要在 accept() 发生后循环。

#!/usr/bin/env python
import socket
import pickle
import pandas as pd

HEADERSIZE = 10

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(),1236))
s.listen(5)  # only one client at a time, but let up to five wait in line
    
while True:
    clientsocket, address = s.accept()
    print(f"Connection from {address} has been established!")

    while senddata:
        # FIXME: refresh dfwebsites every time through this loop?
        d = pd.DataFrame(dfwebsites)
        msg = pickle.dumps(d)
        msg = bytes(f'{len(msg):<{HEADERSIZE}}','utf-8')+msg    
        try:
            clientsocket.send(msg)  #type of bytes is utf-8
        except socket.error as exc:
            print(f"Ending connection from client {address} due to {exc}")
        # FIXME: Do the below only when you want to disconnect a client
        #senddata = False
    clientsocket.close()