[英]Php server socket receiving continuous data from python client socket
[英]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.