Skip to content

Instantly share code, notes, and snippets.

@arseniyturin
Created November 3, 2021 20:40
Show Gist options
  • Save arseniyturin/b0a6e75facdaf96344832d6013e8b1c6 to your computer and use it in GitHub Desktop.
Save arseniyturin/b0a6e75facdaf96344832d6013e8b1c6 to your computer and use it in GitHub Desktop.
# simplest
import socket
from threading import Thread
def response(client, address):
print(f'Client connected from: {address}')
while True:
# receiving message
message = client.recv(1024)
if not message:
break
# send message back to client
client.send(message)
def echo_server(host='', port=8000):
# create socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
# reuse the same port if server was interrupted
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
# claim port number
sock.bind((host, port))
# listen to requests
sock.listen()
# infinite loop
while True:
# client connected
client, address = sock.accept()
# start new thread for each client
Thread(target=response, args=(client, address)).start()
if __name__ == '__main__':
echo_server('', 8000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment