Python implementation of the use of Telnet login chat room instance

Source: Internet
Author: User
Tags datetime readline socket thread class

This example describes the Python implementation of the use of Telnet login chat room. Share to everyone for your reference. Specifically as follows:

A simple chat room that was written while studying Python at home can be logged in using Telnet.

Unfortunately, the support of Chinese is very poor now, English chat is no problem.

The function is simple, it should not be as strong as you think, but you can try if you are interested.

In addition, what surprises me is that it can run on the Android tablet on the sl4a Python interpreter (needing to change a little bit of code, which seems to be the code, I don't remember).

Now this one can run on the PC.

Not much nonsense, directly put the code, just a py file, and the comments are messy, coding style is not good (like I am using the Class C language habit).

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 5, 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 11 9 120 121 122 123 124 125 126 127 128 # Filename:ChatRoomServer.py Import Threading Import datetime Import Socket # A simple log function Def log (LG): Print (l g) # Chat Room Server Listen thread class, this class was use for listening client login # When a client request to connect Server, this class would start a Connect thread class Serverlistenthread (threading. Thread): Def __init__ (self, hostname, port, accept): Threading. Thread.__init__ (self) self.hostname = hostname Self.port = Port Self.accept = Accept Self.sock = Socket.socket (socket.af_i NET, Socket. SOCK_STREAM) self.sock.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1) self.sock.bind ((hostname, port)) Self.sock.listen (0) log (' serverip:%s serverport:%s for client ... '%self.sock.getsockname ()) def run (self): ClientID = 1 while true:client, Cltadd = self.sock.accept () log (' A request F Rom id=%s%s '% ('%d address: '%clientid, Cltadd) ' If Self.accept (ClientID, client): ClientID = ClientID + 1 # Connect thread Class, this class are use for connecting with clientand receiving client ' s message Class Serverconnectthread (threading. Thread): Def __init__ (self, ClientID, client, encoding, receive, disconnect): threading. Thread.__init__ (self) self.client = client Self.clientid = ClientID self.encoding = Encoding self.receive = Receive SELF.D Isconnect = Disconnect Self.clientname = None self.inputs = self.client.makefile (' RB ', 0) self.outputs = Self.client.makef Ile (' WB ', 0) def run (self): self.sendstring (' Input Your Name: ') while true:string = Self.readline () If string:string = S Tring.lstrip () If Len (string) >0:self.receive (self, string) Else:self.inputs.close () Self.outputs.close () Break if Self.clientname:self.disconnect (self) def sendstring (Self, string): Self.sendbytes (Bytes (string, self.encoding)) def Sendbytes (Self, BTS): Self.outputs.write (BTS) def readline (self): rec = self.inputs.readline () If rec:string = Bytes.deco De (REC, self.encoding) if Len (string) >2:string = string[0:-2] else:string = ' else:string = False return string# Chat Room Server class, this class is constitute of a listen thread and many connect thread class Chatroomserver:def __ Init__ (self, ip= ' 0.0.0.0 ', port=9113, encoding= ' Utf-8 '): self.hostname = IP self.encoding = Encoding Self.port = Port Self . Clients = {} Self.clientnames = {} def whenconnect (self, ClientID, client): Log (' A connect with id=%s%s '% ('%d address: '%c Lientid, Client.getpeername ()) connect = Serverconnectthread (ClientID, client, self.encoding, Self.whenreceive, Self.whenexit) Connect.start () return True def whenreceive (self, Client, string): Log (' Frome%d, receive:%s (%d) '% (client . ClientID, String, Len (string)) if Client.clientname:if string[0]== '. ': Self.handlecmd (client, string[1:]) Else:now = d Atetime.datetime.now () sendstring = '%s%srn%srn '% (now, Client.clientname, String) Self.sendtoall (sendstring, client) Else:if self.clientnames.__contains__ (String): Client.sendstring ('%s is exited!!! RN '%string else:client.clientname = string client.sendstring (' Hell,%s!!! RN '%client.clientname self.addclient (client) return True def whenexit (self, client): self.delclient (client) return True def handlecmd (self, client, cmd): Log (' cmd:%s '%cmd) if cmd== ' user ': client.sendstring (' user list (%d): Rn '%len ( self.clients)) for i in SELF.CLIENTS:CLT = Self.clients[i] client.sendstring ('%DT%SRN '% (Clt.clientid, clt.clientname)) else:client.sendstring (' unknow command:%s:rn '%cmd) def start (self): Serverlisten = Serverlistenthread (Self.hostname, Self.port, Self.whenconnect) Serverlisten.start () def sendtoall (self, string, notfor): Sends = bytes (String, self.encoding) for I-Self.clients:if not (Notfor and notfor.clientid==i): Self.clients[i].sendbytes (sends) def Addclie NT (self, Client): Self.sendtoall ('%s logined!!! RN '%client.clientname, client ' self.clients[client.clientid] = client Self.clientnames[client.clientname] = Client.clientid def delclient (self, client): Self.sendtoall ('%s logouted!!! RN '%client.clientname, client) del Self.clients[client.clientid] del sElf.clientnames[client.clientname] # Start a chat room server Chatroomserver (). Start ()

With this server program after it (of course, if you install the Python interpreter), there is no client, then you will ask how to start chatting?

Here's how to start chatting, first you run the file, and the following figure lets you see the server waiting for the client to log in:

The client directly uses the Telnet command to log in, note that the port should be the same as the server, the command is: Telnet 127.0.0.1 9011, automatically open the Telnet console, enter your name it:

Now you are looking at the server side of the console interface, you can see logged the login message:

After you continue using Telnet to log on to another user, you can chat:

The function is very simple, but this reminds me of twenty or thirty years ago, hey, it should be such a chat at that time, born in this era we will never realize that kind of fun.

I hope this article will help you with your Python programming.

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.