Skip to content

Instantly share code, notes, and snippets.

@henrikno
Last active March 4, 2021 20:46
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 henrikno/1c5ed33e52869fe611790768284f9dd6 to your computer and use it in GitHub Desktop.
Save henrikno/1c5ed33e52869fe611790768284f9dd6 to your computer and use it in GitHub Desktop.
Python Multithreaded TCP server example
#!/usr/bin/python
import socket # Import socket module
from threading import Thread
def on_new_client(clientsocket, addr):
try:
while True:
msg = clientsocket.recv(1024)
if not msg:
break
print(addr, ' >> ', str(msg, 'utf-8'))
# echo the message back
clientsocket.send(msg)
finally:
print('Connection to client', addr, 'closed')
clientsocket.close()
s = socket.socket() # Create a socket object
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
port = 50000 # Reserve a port for your service.
s.bind(('127.0.0.1', port)) # Bind to the port
s.listen(5) # Now wait for client connection.
print('Server started!')
try:
while True:
c, addr = s.accept() # Establish connection with client.
print('Got connection from', addr)
Thread(target=on_new_client, args=(c,addr)).start()
finally:
s.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment