Simple TCP-echo client-server

########################################################## ########################################################## # The server code. #!/usr/bin/python # -*- coding: utf-8 -*- import sys import socket import threading clients = [] sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) HOST = "localhost" PORT = 12345 sock.bind((HOST, PORT)) sock.listen(100) print("server started") class Thread(threading.Thread): def __init__(self, client): threading.Thread.__init__(self) self.conn = client[0] self.addr = client[1] print("got connection from: ", self.addr) def run(self): try: while True: if self.conn not in clients: clients.append(self.conn) data = self.conn.recv(1024) if data: print("taken: ", data.decode(), "from:", self.addr) for client in clients: client.send(bytes(data.decode(), encoding = "UTF-8")) except ConnectionResetError: print("client: ", self.addr, "Disconnected") while True: client = sock.accept() clientThread = Thread(client) clientThread.start() ########################################################## ########################################################## # The client code. #/usr/bin/python # -*- coding: utf-8 -*- import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = "localhost" port = 12345 sock.connect((host, port)) while True: message = input("Enter message: ") sock.send(bytes(message, encoding = "UTF-8")) print("recieve a message:", sock.recv(1024).decode()) sock.close()

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.