繁体   English   中英

从服务器python发送连续数据到客户端

[英]Send Continuous Data to Client from Server python

我正在编写一个程序,以将数据从服务器连续发送到客户端。 在这里,我使用时间戳作为示例将其发送到已连接的多个客户端。 我使用了多线程来支持多个客户端。 我希望将时间每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

服务器端

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM