【问题标题】:Send Continuous Data to Client from Server python从服务器python向客户端发送连续数据
【发布时间】:2019-03-20 07:53:32
【问题描述】:

我正在编写一个程序,将数据从服务器连续发送到客户端。在这里,我使用时间戳作为示例将其发送给连接的多个客户端。我使用多线程来支持多个客户端。我希望每 10 秒向客户端发送一次时间。但在我的代码中,客户端在收到第一个数据后停止。如何让客户端连续接收数据。我尝试在客户端添加 while 循环,但它无法实现。大家有什么建议

这是示例代码: 服务器端:

import socket
import os
from threading import Thread
import thread
import threading
import time
import datetime

def listener(client, address):
    print "Accepted connection from: ", address
    with clients_lock:
        clients.add(client)
    try:    
        while True:
            data = client.recv(1024)
            if not data:
                break
            else:
                print repr(data)
                with clients_lock:
                    for c in clients:
                        c.sendall(data)
    finally:
        with clients_lock:
            clients.remove(client)
            client.close()

clients = set()
clients_lock = threading.Lock()

host = socket.gethostname()
port = 10016

s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(3)
th = []

while True:
    print "Server is listening for connections..."
    client, address = s.accept()
    timestamp = datetime.datetime.now().strftime("%I:%M:%S %p")
    client.send(timestamp) 
    time.sleep(10)
    th.append(Thread(target=listener, args = (client,address)).start())
s.close()

客户端:

import socket
import os
from threading import Thread


import socket
import time

s = socket.socket()  
host = socket.gethostname()        
port = 10016



s.connect((host, port))
print (s.recv(1024)) 
s.close() 


# close the connection 

我的输出:

01:15:10

客户端所需的输出:

01:15:10
01:15:20
01:15:30
#and should go on

【问题讨论】:

    标签: python python-3.x multithreading sockets python-sockets


    【解决方案1】:

    服务器端

    while True:
        client, address = s.accept()
        th.append(Thread(target=listener, args = (client,address)).start())
    s.close()
    

    在 def listener() 中更改 while 循环以像这样为每个线程连续发送数据

    while True:
            data = client.recv(1024)
            if data == '0':
                timestamp = datetime.datetime.now().strftime("%I:%M:%S %p")
                client.send(timestamp)
                time.sleep(2)
    

    在客户端在while循环中添加此行以发送一些数据以满足if条件

    s.connect((host, port))
    while True:
        s.send('0')
        print(s.recv(1024))
    #s.close()
    

    【讨论】:

    • 谢谢。有效。但是当我想使用相同的客户端代码在另一个终端上执行另一个客户端时。它不起作用。同时另一个客户端也想接收相同的数据。如何制作。
    • 更新了解决方案,这将提供您想要的。问题首先是您需要为每个线程连续发送数据,因此需要更改侦听器函数,然后如果条件不正常,您就不会从客户端发送任何数据。
    • 这行得通。所以尝试解决方案,如果出现问题,请告诉我
    猜你喜欢
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    • 2017-05-02
    • 1970-01-01
    • 2015-02-17
    相关资源
    最近更新 更多