Created
October 26, 2019 02:27
-
-
Save fernandorovai/5524118f9ed3c04189dd1a61aea4dc28 to your computer and use it in GitHub Desktop.
socket_multiClient
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket # Import socket module | |
import threading # Handle Threads | |
import time | |
import json | |
lock = threading.Lock() | |
i = [0] | |
def updateVal(): | |
while True: | |
i[0] = i[0]+1 | |
time.sleep(2) | |
def handle(connAddr, j): | |
print("New connection") | |
conn = connAddr[0] | |
while True: | |
time.sleep(2) | |
with lock: | |
conn.send(str(j[0]).encode()) | |
s = socket.socket() # Create a socket object | |
host = socket.gethostname() # Get local machine name | |
port = 50000 # Reserve a port for your service. | |
print ('Server started!') | |
print ('Waiting for clients...') | |
try: | |
s.bind((host, port)) # Bind to the port | |
s.listen(5) # Now wait for client connection. | |
except Exception as e: | |
print(e) | |
# Thread that will update the var i | |
threading.Thread(target=updateVal, args=()).start() | |
while True: | |
t = threading.Thread(target=handle, args=(s.accept(),i)) | |
t.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment