基于socketserver的python多线程聊天室

本文介绍了如何使用Python3的socketserver模块创建一个多线程的聊天室。在Python3中,由于数据读写基于byte,所以发送和接收字符数据时需要进行编码和解码操作。而在Python2.x中,字符串处理不同,无需此步骤。示例代码包括了服务器端和客户端的实现。
摘要由CSDN通过智能技术生成

在python3中,socketserver提供的读写是基于byte字节的。故发送字符数据需要先编码。接受到的数据需要解码。

而Python2.x 中。没有字节的概念。只有两种字符串:表示 str 和 unicode 。故py2不必encode/decode

#Talk is cheep, show you the code.


server:

"""everytime before you send msg, encode it
after you rec msg, decode it!
"""

import socketserver
import re
import socket

class ClientError(Exception):
	"An exception thrown because the client gave bad input to the server."
	pass

class PythonChatServer(socketserver.ThreadingTCPServer):
	"the server class"
	
	def __init__(self, server_address, RequestHandlerClass):
		"""Set up an initially empty mapping between a user' s nickname
		and the file-like object used to send data to that user."""
		socketserver.ThreadingTCPServer.__init__(self, server_address, RequestHandlerClass)
		self.users = {}

class RequestHandler(socketserver.StreamRequestHandler):
	"""Handles the life cycle of a user's connection to the chat server: connecting,
	chatting, running server commands, and disconnecting."""
	
	NICKNAME = re.compile('^[A-Za-z0-9_-]+$') #regex for a valid nickname
	
	def handle(self):
		"""Handles a connection: gets the user's nickname, then
		processes input from the user until they quit or drop the
		connection."""
		self.nickname = None
		
		self.privateMessage("Who are you?")
		nickname=self._readline()
		done = False
		try:
			self.nickCommand(nickname)
			self.privateMessage('Hello %s, welcome to the Python Chat Server.' % nickname)
			self.broadcast('%s has joined the chat.' %nickname,False)
			#print('%s has joined the chat.' %nickname) #print in server
		except (ClientError) as error:
			self.privateMessage(error.args[0])
			done = True
		except socket.error:
			done = True
		
		#Now they're logged in, let them c
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值