Implementing a Simple UDP Chatroom with Python Sockets
This article explains the fundamentals of socket programming in Python by demonstrating how to build a lightweight UDP-based chatroom, covering socket creation, common methods, and complete server‑client examples with code snippets for multi‑user communication.
Sockets are the endpoints of two‑way communication channels that can operate within a single process, between processes on the same machine, or across different hosts, enabling network programming in Python.
The socket module provides a generic interface and specific classes for various transport types such as Unix domain sockets, TCP, and UDP.
1.1 socket module
To create a socket, use the s = socket.socket(socket_family, socket_type, protocol=0) syntax.
1.2 Common methods
Typical socket operations include binding, sending, and receiving data, which are demonstrated in the following examples.
2. Example 1 – Server (UDP)
<code>#sever.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("来自服务器" + str(addr) + "的消息:")
print(receive_data.decode('utf-8'))
msg = input('please input send to msg:')
s.sendto(msg.encode('utf-8'),addr)
except:
s.close()
</code>2.2 Client (UDP)
<code>#client.py
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
try:
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("来自服务器" + str(addr) + "的消息:")
print(msg.decode('utf-8'))
except:
s.close()
</code>These basic scripts provide a functional UDP chatroom where multiple clients communicate through a single server.
3. Optimized Example – Multi‑user UDP Chatroom
Server
<code>#server.py
import socket
import logging
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 创建socket对象
addr = ('127.0.0.1', 9999)
s.bind(addr) # 绑定地址和端口
logging.info('UDP Server on %s:%s...', addr[0], addr[1])
user = {} # 存放字典{addr:name}
while True:
try:
data, addr = s.recvfrom(1024) # 接收客户端消息
if not addr in user:
for address in user:
s.sendto(data + ' 进入聊天室...'.encode('utf-8'), address)
user[addr] = data.decode('utf-8')
continue
if 'EXIT'.lower() in data.decode('utf-8'):
name = user[addr]
user.pop(addr)
for address in user:
s.sendto((name + ' 离开了聊天室...').encode(), address)
else:
print('"%s" from %s:%s' % (data.decode('utf-8'), addr[0], addr[1]))
for address in user:
if address != addr:
s.sendto(data, address)
except ConnectionResetError:
logging.warning('Someone left unexcept.')
if __name__ == '__main__':
main()
</code>Client
<code>#clinet.py
import socket
import threading
def recv(sock, addr):
'''
一个UDP连接在接收消息前必须要让系统知道所占端口
也就是需要send一次,否则win下会报错
'''
sock.sendto(name.encode('utf-8'), addr)
while True:
data = sock.recv(1024)
print(data.decode('utf-8'))
def send(sock, addr):
'''
发送数据的方法
参数:
sock:定义一个实例化socket对象
server:传递的服务器IP和端口
'''
while True:
string = input('')
message = name + ' : ' + string
data = message.encode('utf-8')
sock.sendto(data, addr)
if string.lower() == 'EXIT'.lower():
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()
</code>This optimized version supports multiple users, handles user join/leave notifications, and uses threading on the client side to enable simultaneous sending and receiving.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
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.