Skip to content

Instantly share code, notes, and snippets.

@fernandorovai
Created October 26, 2019 02:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fernandorovai/5524118f9ed3c04189dd1a61aea4dc28 to your computer and use it in GitHub Desktop.
Save fernandorovai/5524118f9ed3c04189dd1a61aea4dc28 to your computer and use it in GitHub Desktop.
socket_multiClient
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