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

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

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

关于python - 从服务器 python 向客户端发送连续数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55255869/

相关文章:

python - 这个字符串匹配方法在python中有实现吗?

python - 如何检测并绘制 asc 文件的强度

python - 最大成对产品快速解决方案

java - 线程循环卡住游戏窗口

c++ - 是否可以获取正在监听 Windows 端口的进程的线程 ID?

python - 如何在 PyQt 中使用按钮在 while 循环中退出程序

python - 是否可以使用 python 在 Dialogflow 中触发意图?

python - 如何将图像加载到 python 3.4 tkinter 窗口中?

Python - 如何将 while 循环中的值存储到 pandas 数据框中?

python - 在 start_new_thread 之后加入线程