[Python-*-Reading] basic Python tutorial-virtual Tea Party

Source: Internet
Author: User

In general, a server client that only supports one chat room uses Telnet

Books: Python Data Summary

Python tutorial here is the source code in Chapter 24th. It is used for practice research.

# Coding: utf8 # python2.7 chatser2.py # a slightly more complex chatting room server ''' after using python to start the service telnet connection, it can become a Simple Chat Server first login: Login Name logout: logout speak: Say to check who has logged on to the server: WHO to view the person in the same room: look simple example: Telnet localhost 50005 welcome to testchatlogin tianshidiyu has entered the room. nihunknown command: ihsay nihaotianshi: nihaodiyu: niyehao ''' from asyncore import dispatcher from asynchat import async_chatimport socketimport asyncorehost = 'po RT = 50005 serverconf = (host, Port) name = 'testchat' class endsession (exception): pass class commandhandler (object ): '''command parsing class ''' def unknown (self, session, CMD): 'responds to unknown command 'session. push ('unknown command: % s \ r \ n' % cmd) def handle (self, session, line ): 'COMMAND for parsing information sent from the client and content 'if not line: Print 'Please write a command... 'If not line. strip (): Print 'get a line: ', line return parts = line. split ('', 1) # command separation Cmd = parts [0] Try: line = parts [1]. strip () handle T indexerror: line = ''# Call the corresponding Method Processing Command meth = getattr (self, 'Do _ '+ cmd, none) try: # Call the meth (Session, line) method t typeerror: Self. unknown (Session, CMD) class room (commandhandler): ''' includes a generic environment for one or more users (sessions. Processes basic commands and broadcasts ''' def _ init _ (self, server): Self. server = server self. sessions = [] def add (self, session): 'Add a user' self. sessions. append (Session) def remove (self, session): 'A user leave 'self. sessions. remove (Session) def broadcast (self, line): 'Give all session in the room a line' for session in self. sessions: Session. push (line) def do_logout (self, session, line): 'response logout command 'raise endsession class Loginroom (room): ''' room for the user just logged in ''' 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 login \ nuse "Login <Nick>" \ r \ n') def do_login (self, session, line): name = line. strip () # a user name if not name: session must be specified during login. push ('Please enter a name \ r \ n') Elif name in self. server. users: # the user name cannot be repeated? Session. Push ('the name "% s" is taken! \ R \ n' % name) session. push ('Please try again. \ r \ n') else: Session. name = Name session. enter (self. server. main_room) Class chatroom (room): ''' the room ''' def add (self, session): # Tell all new one come self. broadcast (Session. name + 'has entered the room. \ r \ n') self. server. users [session. name] = session room. add (self, session) def remove (self, session): Room. remove (self. session) # Tell all the user logout self. broadcast (Session. name + 'has left the room \ r \ n') def do_say (self, session, line): Self. broadcast (Session. name + ':' + LINE + '\ r \ n') def do_look (self, session, line): 'Look who is in the room 'session. push ('the following are in this room: \ r \ n') for other in self. sessions: Session. push (Other. name + '\ r \ n') def do_who (self, session, line): 'check who has logged on to 'session. push ('the following are logged in: \ r \ n') for name in self. server. users: Session. push (name + '\ r \ n') Class logoutroom (room): ''' the room prepared for a single user, only used to remove ''' def add (self, session) from the server: Try: del self. server. users [session. name] cipher t keyerror: pass class chatsession (async_chat): ''' a single session, responsible for communicating with the user ''' def _ init _ (self, server, sock ): async_chat. _ init _ (self, sock) self. server = server self. set_terminator ('\ r \ n') self. data = [] self. name = none # log on to self from here for all sessions. enter (loginroom (server) def enter (self, room): Try: cur = self. room counter t attributeerror: Pass self. room = room. add (Self) def collect_incoming_data (self, data): Self. data. append (data) def found_terminator (Self): line = ''. join (self. data) self. data = [] Try: Self. room. handle (self, line) handle T endsession: Self. handle_close () def handle_close (Self): async_chat.handle_close (Self) self. enter (logoutroom (self. server) Class chatserver (dispatcher): ''' there is only one room Chat Server ''' def _ init _ (self, serverconf, name): dispatcher. _ init _ (Self) self. create_socket (socket. af_inet, socket. sock_stream) self. set_reuse_addr () # The last port number self can be reused. BIND (serverconf) self. listen (5) self. name = Name self. users = {} self. main_room = chatroom (Self) def handle_accept (Self): Conn, ADDR = self. accept () chatsession (self, Conn) # main function if _ name __= = '_ main _': S = chatserver (serverconf, name) Try: asyncore. loop () handle T keyboardinterrupt: Print 'server exception... quit'

Result

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.