Build a Simple UDP Chatroom with Python Sockets – Step‑by‑Step Guide
This article explains socket fundamentals and walks through creating a simple UDP‑based chatroom in Python, covering basic socket creation, common methods, a straightforward server‑client example, and an enhanced multi‑user implementation with full source code and execution details.
1. Introduction
Sockets are endpoints of a two‑way communication channel. They can be used for inter‑process communication on the same machine or across different hosts that have Internet connectivity.
2. Socket module
To create a socket you call socket.socket() with the family, type and optional protocol arguments:
s = socket.socket(socket_family, socket_type, protocol=0)3. Common methods
Typical socket methods used in the examples include bind(), sendto(), recvfrom(), and close().
4. Example 1 – Simple UDP chat
4.1 Server
# server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = socket.gethostname()
port = 8088
s.bind((host, port))
try:
while True:
receive_data, addr = s.recvfrom(1024)
print("From server " + str(addr) + " message:")
print(receive_data.decode('utf-8'))
msg = input('please input send to msg:')
s.sendto(msg.encode('utf-8'), addr)
except:
s.close()4.2 Client
# client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
host = socket.gethostname()
port = 8088
send_data = input('please input msg:')
s.sendto(send_data.encode('utf-8'), (host, port))
msg, addr = s.recvfrom(1024)
print("From server " + str(addr) + " message:")
print(msg.decode('utf-8'))5. Optimized multi‑user chatroom
5.1 Server
# server.py
import socket, logging
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
addr = ('127.0.0.1', 9999)
s.bind(addr)
logging.info('UDP Server on %s:%s...', addr[0], addr[1])
users = {}
while True:
try:
data, addr = s.recvfrom(1024)
if addr not in users:
for address in users:
s.sendto(data + b' 进入聊天室...', address)
users[addr] = data.decode('utf-8')
continue
if 'exit' in data.decode('utf-8').lower():
name = users.pop(addr)
for address in users:
s.sendto((name + ' 离开了聊天室...').encode(), address)
continue
print('"%s" from %s:%s' % (data.decode('utf-8'), addr[0], addr[1]))
for address in users:
if address != addr:
s.sendto(data, address)
except ConnectionResetError:
logging.warning('Someone left unexpectedly.')
if __name__ == '__main__':
main()5.2 Client
# client.py
import socket, threading
def recv(sock, server):
"""Receive messages; a UDP socket must send once before receiving on Windows."""
sock.sendto(name.encode('utf-8'), server)
while True:
data = sock.recv(1024)
print(data.decode('utf-8'))
def send(sock, server):
"""Send messages."""
while True:
string = input()
message = name + ' : ' + string
data = message.encode('utf-8')
sock.sendto(data, server)
if string.lower() == 'exit':
break
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server = ('127.0.0.1', 9999)
tr = threading.Thread(target=recv, args=(s, server), daemon=True)
ts = threading.Thread(target=send, args=(s, server))
tr.start()
ts.start()
ts.join()
s.close()
if __name__ == '__main__':
print("-----欢迎来到聊天室,退出聊天室请输入'EXIT(不分大小写)'-----")
name = input('请输入你的名称:')
print('-----------------%s------------------' % name)
main()This simple UDP chatroom supports multiple users communicating through a single server.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
