Last active
March 4, 2021 20:46
-
-
Save henrikno/1c5ed33e52869fe611790768284f9dd6 to your computer and use it in GitHub Desktop.
Python Multithreaded TCP server example
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
#!/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