Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Python socket based chat server
import socket, sys, threading
# Simple chat client that allows multiple connections via threads
PORT = 9876 # the port number to run our server on
__version__ = "0.0.1"
class ChatServer(threading.Thread):
def __init__(self, port, host='localhost'):
self.port = port = host
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.users = {} # current connections
self.server.bind((, self.port))
except socket.error:
print('Bind failed %s' % (socket.error))
# Not currently used. Ensure sockets are closed on disconnect
def exit(self):
def run_thread(self, conn, addr):
print('Client connected with ' + addr[0] + ':' + str(addr[1]))
while True:
data = conn.recv(1024)
reply = b'OK...' + data
conn.close() # Close
def run(self):
print('Waiting for connections on port %s' % (self.port))
# We need to run a loop and create a new thread for each connection
while True:
conn, addr = self.server.accept()
threading.Thread(target=self.run_thread, args=(conn, addr)).start()
class ChatClient(object):
def __init__(self, port, host='localhost'): = host
self.port = port
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((, port))
def send_message(self, msg):
if __name__ == '__main__':
server = ChatServer(PORT)
# Run the chat server listening on PORT
# Send a message to the chat server
client = ChatClient(PORT)
client.send_message("Oh hai!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment