Basic Chat program
Let's start with a basic test example:
main.py
From Asyncore Import Dispatcher
import socket,asyncore
PORT = 11223
class Chatserver (Dispatcher):
def __init__ (self, port):
dispatcher.__init__ (self)
self.create_socket (socket.af_inet, socket. SOCK_STREAM)
self.set_reuse_addr ()
self.bind ((', port) Self.listen (
5)
def handle_accept (self) :
conn,addr = self.accept ()
print (' Connection attempt from ', addr[0])
if __name__ = ' __main__ ':
s = Chatserver (PORT)
try:asyncore.loop ()
except Keyboardinterrupt:pass
Above is the server segment program, after receiving the connection immediately on the server to display the other IP, but does not remain connected. The client test is very simple, you can write a socket connection, you can also in order to save trouble directly local to open telnet on the line, open Telnet method is, in the Start menu search:
Then make sure, then cmd directly telnet on the line.
Run the main.py above, and then the client links the server:
Cmd->telnet:open 127.0.0.1 11223
The above is a basic Python server scripting process. The next step is to implement a basic chat program for practicing.
Basic functionality of implementation (virtual tea session) test environment The Code on the basic tutorial for Python 3.6.0[python cannot run directly on version 3.6.0, following is a modified virtual tea session.
Function:
Login name Logon Room
Logout out of the room.
Say XXXX Spoke
Look at the people in the same room
Who to see who logged on to the current server
Test screenshot
Simple to say the design structure:
CommandHandler class: Handles the command, the function exists executes, does not exist then goes directly unknown function. Combining the try and GetAttr functions Python can directly try to execute an indeterminate function that does not exist. [I've been thinking about how other languages are going to achieve this, creating a virtual factory. To remember, simply create some functions and then format the function names in a void pointer container. function formatting to unify]
Room class: Represents a room, there are some of the room people [link] data structure of the addition of deletion operations, as well as related broadcast functions, used to send the message to everyone.
Loginroom class, which has a successful landing room, landing room failure and landing operations, such as greeting the lander, while notifying others of the details of landing.
Logoutroom class, log out of the room class, the user log out of the room when some of the data structure processing.
Chatroom class, Chat room class, the main is to encapsulate some functional functions. such as say look who and so on.
Chatsession,chatserver Class Basic Server program needs, respectively inherit async_chat and dispatcher, handle some server parameters, and overload set some processing functions.
Detailed code is as follows [note This code is tested in python3.6.0]
#!/usr/bin/env python3 __author__ = ' tcstory ' from Asyncore Import dispatcher from asynchat import async_chat import Socke T, Asyncore port=5005 name= ' Testchat ' class EndSession (Exception): Pass class CommandHandler: "Simple com Mand handler similar to CMD.
CMD from the standard library ' def unknown (self, Sessions, cmd): ' Respond to a unknown command ' Session.push (' unkonw command: {0}\r\n '. Format (cmd). Encode ()) def handle (self, session, line): ' Handle a R
Eceived line from a given sessions ' if not Line.strip (): Return #Split off the command Parts = Line.split (', 1) cmd = parts[0] Try:line=parts[1].strip () except Indexerror : Line= ' #Try to find a handler meth=getattr (self, ' do_ ' +cmd,none) Try: #A Ssume it ' s callable meth (session,line) except TypeError: #If it isn ' t, respond to theUnknown command Self.unknown (Session,cmd) class Room (CommandHandler): "A generic environment that
May contain one or more users (sessions). It takes care of basic command handling and broadcasting.
' Def __init__ (self,server): Self.server=server self.sessions=[] def add (self,session): ' A session (user) has entered the room ' Self.sessions.append (session) def remove (self,session): ' A Session (user) has left the room ' Self.sessions.remove (session) def broadcast (self,line): ' Send a li NE to all sessions in the room ' for sessions in Self.sessions:session.push (Line.encode ()) def do
_logout (self,session,line): ' Respond to the logout command ' Raise EndSession class Loginroom (Room): "A room meant for a" who has just connected ' def Add (self,session): Room.add (self , session) #When a user Enters,greet Him/Her Self.broadcast (' Welcome to {0}\r\n '. Format (self.server.name)) def unknown (self, Session, CMD): #All Unknown commands (anything except login or logout) #results in a prodding session.push (' please lo G In\nuse "Login <nick>" \ r \ n Encode ()) def do_login (self,session,line): Name=line.strip () #Ma
Ke sure the user has entered a name if not Name:session.push (' Please enter a name\r\n '. Encode ()) #Make sure that's name isn ' t in-elif name in Self.server.users:session.push (' the name {0} i
S taken.\r\n '. Format (name). Encode ()) Session.push (' Please try Again.\r\n '. Encode ()) Else: #The The name is Ok,os it's stored in Session.and #the user is moved into the main room SESSION.N Ame=name Session.enter (Self.server.main_room) class chatroom (room): ' A room meant for multiple us ERs who can chat with the others in the room ' def Add (self,session): #Notify Everyone that a new user has entered SEL
F.broadcast (' {0} has entered the room.\r\n '. Format (session.name)) self.server.users[session.name]=session Room.add (self,session) def remove (self,session): Room.remove (self,session) #Notify everyone that a U Ser has left self.broadcast (' {0} has left the room.\r\n '. Format (session.name)) def Do_say (Self,session,line) : Self.broadcast (' {0}: ' +line+ ' \ r \ n '). Format (session.name)) def do_look (self,session,line): ' Handle
s the look command,used to, who's in a Room ' Session.push (' The following are into this room:\r\n '. Encode ()) For the other in Self.sessions:session.push (' {0}\r\n '. Format (other.name). Encode ()) def do_who (self,sess Ion,line): ' Handles's command, used to-who-logged in ' Session.push (' the following are
In:\r\n '. Encode ()) For name in Self.server.users:session.push (' {0}\r\n '. Format (name). Encode ()) class Logoutroom (Room): ' A simple room for a single user. Its sole purpose are to remove the user ' s name from the server ' def Add (self,session): #When a session (user) enters the logoutroom it is deleted Try:del Self.server.users[session.name] except Keyerror:pass class Chatsession (async_chat): ' A single Session,which takes care of the Communica tion with a single user ' Def __init__ (self,server,sock): # async_chat.__init__ (self,sock) SUP ER (). __init__ (sock) self.server=server self.set_terminator (b ' \ r \ n ') self.data=[] Self.name =none #All sessions begin in a separate loginroom self.enter (loginroom (server)) def enter (Self,room) : # Remove self from the room and add self to next room ... try:cur=self.Room except Attributeerror:pass else:cur.remove (self) self.room=room Room.add (self) def collect_incoming_data (self, data): Self.data.append (Data.decode (' Utf-8 ')) def found_termin
Ator (self): line= '. Join (Self.data) self.data=[] Try:self.room.handle (self,line)
Except EndSession:self.handle_close () def handle_close (self): Async_chat.handle_close (self)
Self.enter (Logoutroom (self.server)) class Chatserver (Dispatcher): ' A chat server with a single room ' Def __init__ (self,port,name): Super (). __init__ () # dispatcher.__init__ (self) self.cr Eate_socket (Socket.af_inet,socket.
SOCK_STREAM) self.set_reuse_addr () 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.loo P () except Keyboardinterrupt:print ()