Send dynamically updating data from python server to many clients

762 Views Asked by At

first I'll apologise if I've made some large error, I'm new to python. I'm trying to write software using python sockets to generate a random number every 10 seconds and send it to multiple clients. So far I have been able to create a server and connect multiple clients, but the random numbers that are being generated and sent to each client are different. I'm trying to make them the same.

Here is my server code:

import sys, time, socket, threading, random

def newClient(c):
    global data
    c.send("Connected to stream".encode())
    while True:
        c.sendall(str(data).encode())
        time.sleep(10)

def setData():
    data = random.random()
    return data

def readData():
    global data
    while True:
        data = setData()

port = 12312
ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssock.bind(('', port))
ssock.listen(5)

data = random.random()
threading.Thread(target=readData).start()

while True:
    c, addr = ssock.accept()
    print("[-] Connected to " + addr[0] + ":" + str(addr[1]))
    threading.Thread(target=newClient, args=(c,)).start()

If someone could point me in the right direction, so that my server sends the same data to both clients, I would be very grateful.

0

There are 0 best solutions below