在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