This article mainly for you in detail the Python Basic Tutorial project Five virtual Tea Party, with a certain reference value, interested in small partners can refer to
Almost every time you learn or use any programming language, there is never a little bit of practice about sockets, especially when it comes to writing some local area network communications. So this project in the book just can practice socket programming.
The overall idea of this exercise first has a chat server, the function of this server is mainly to provide client socket connection, store each client connection session, processing each connection sent messages, parsing the data sent by the client. In this case, the client side does not need to write code, using the system's Telnet tool.
I think with the above analysis, the rest of the program will have nothing to say, of course, except those two sockets encapsulated class.
Using the socket class in Python, I tried to write a simple communication program, but somehow there was always an accident in the communication. This simple code is as follows:
server.py
Import Socketmysocket = Socket.socket (socket.af_inet,socket. Sock_stream) Mysocket.bind (("", 8888)) Mysocket.listen (5) while True: connection,addr = mysocket.accept () Revstr = Connection.recv (1024x768) connection.send (' Server: ' + revstr) connection.close ()
clinet.py
Import Socketimport Timeclientsocket = Socket.socket (socket.af_inet, socket. Sock_stream) Clientsocket.connect (("', 8888)) while True: time.sleep (2) clientsocket.send (' Hello The5fire ') print Clientsocket.recv (1024x768) clientsocket.close ()
The reason for the error in this program is not to be fine-grained, because Python provides two packaged classes to complete the socket communication process: the dispatcher in Asynchat and Asyncore and Asyncore itself. The preceding classes are used to process each session of the client with the server, and the following classes are primarily used to provide the socket connection service. And each socket connection is hosted to the former (async_chat) to handle.
Look at the code:
From Asyncore import dispatcherfrom asynchat import async_chatimport socket, Asyncoreport = 5005NAME = ' Testchat ' class End Session (Exception):p assclass commandhandler:def Unknown (self, Session, CMD): Session.push (' Unknown command:%s\ r\n '% cmd) def handle (self, session, line): If not Line.strip (): Return parts = Line.split (", 1) cmd = parts[0] Try:line = Parts[1].strip () except indexerror:line = ' meth = getattr (self, ' do_ ' + CMD, None) Try:meth (session, line) except TypeError:self.unknown (Session,cmd) class R Oom (CommandHandler): Def __init__ (self, server): Self.server = Server Self.sessions = [] def add (self, session): Self.sessions.append (session) def remove (self, session): Self.sessions.remove (session) def Broadcast (self, line): to session in Self.sessions:session.push (line) def do_logout (self, session, Line): Raise EndSEssionclass Loginroom (Guest): def Add (self,session): Room.add (self,session) self.broadcast (' Welcome to%s\ r\n '% self.server.name) def unknown (self, Session, CMD): Session.push (' Please log in \nuse ' login ' \ r \ n ') def Do_login (self, Session, line): name = Line.strip () If the Name:session.push (' Please enter a Nam e\r\n ') elif name in Self.server.users:session.push (' The name '%s ' is taken.\r\n '% name) se Ssoin.push (' Please try again.\r\n ') Else:session.name = name Session.enter (self.server.main_ ) class chatroom: def add (Self, session): Self.broadcast (Session.name + ' have entered the room.\r\n ') Self.server.users[session.name] = Session room.add (self, session) def remove (self, session): ROOM.R Emove (self, session) Self.broadcast (Session.name + ' have left the room.\r\n ') def Do_say (self, Session, line): Self.broadcast (sesSion.name + ': ' + line + ' \ r \ n ') def do_look (self, Session, line): Session.push (' The following is in this : \ r \ n ') for other in Self.sessions:session.push (Other.name + ' \ r \ n ') def do_who (self, session, line) : Session.push (' The following is logged in:\r\n ') for name in Self.server.users:session.push (NA Me + ' \ r \ n ') class Logoutroom: Def add (Self, session): Try:del Self.server.users[session.name] Exce PT Keyerror:passclass Chatsession (async_chat): Def __init__ (self, server, sock): async_chat.__init__ (Self,sock) Self.server = Server Self.set_terminator (' \ r \ n ') Self.data = [] Self.name = None self. Enter (loginroom (server)) def enter (self, guest): Try:cur = Self.room except Attributeerror: Pass Else:cur.remove (self) self.room = Guest Room.add (self) def collect_incoming_data (s Elf, data): self.Data.append (data) def found_terminator (self): line = '. Join (self.data) Self.data = [] Try:self.r Oom.handle (self, line) except EndSession:self.handle_close () def handle_close (self): async_ch At.handle_close (self) self.enter (Logoutroom (self.server)) class Chatserver (Dispatcher): Def __init__ (self, port, Name): dispatcher.__init__ (self) self.create_socket (socket.af_inet, socket. Sock_stream) Self.bind ((", port)) Self.listen (5) self.name = name self.users = {} self. Main_room = Chatroom (self) def handle_accept (self): conn, addr = Self.accept () chatsession (Self,conn) If _ _name__ = = ' __main__ ': s = chatserver (PORT, name) Try:asyncore.loop () except Keyboardinterrupt:print
The entire program is divided into three parts that I started with:
Provides the client's socket connection: the Chatserver class.
Stores each client's connection session, processing the message sent by each connection: the Chatsession class, which functions very simply, accepts the data and determines if there is a terminator, if there is a method called Found_terminator.
Parse the data sent by the client: the rest of the rooms related classes, which are used to handle the strings and commands sent by the client, are inherited from CommandHandler.
Eventually: