首页 > 解决方案 > 网络服务器只向客户端发送一次数据而不是循环

问题描述

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

我希望我的服务器不断向我的客户端发送数据流,但由于某种原因,在接收到第一条数据后,我的客户端不再接收/打印出任何数据。

我的简化 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

我的客户.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""

为什么它不能接收超过一个数据?

非常感谢你的帮助!我真的很喜欢评论告诉我如何提高我的问题!

标签: pythonpython-3.xsocketsstreampickle

解决方案


要向每个客户端发送多条消息,您需要在事件发生后进行循环。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()

推荐阅读