This example describes the Python implementation of using Telnet to log in to the chat room. Share to everyone for your reference. Specific as follows:
A simple chat room that was written a long time ago at home to learn python, you can use Telnet to log in.
Unfortunately, the support of Chinese is very poor now, English chat is no problem.
The function is simple, it should not be as powerful as you think, but you can try it if you are interested.
In addition, I am surprised that it can run on Android tablet sl4a Python interpreter (need to change a little bit of code, it seems that the coding of the place, I can't remember).
Now this can be run on a PC.
Not much nonsense, directly put the code, just a py file, and the comments are messy, coding style is not good (I am in the habit of using C language).
# Filename:ChatRoomServer.py Import Threading Import datetime Import Socket # A simple log function Def log (LG): Print ( LG) # Chat Class Server Listen thread class, this is the use of listening client login # When a client request to Connec T 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.so Cket (socket.af_inet, 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 waiting F or client ... '%self.sock.getsockname ()) def run (self): ClientID = 1 while true:client, Cltadd = Self.sock. Accept () log (' A request from id=%s%s '% ('%d Address: '%clientid, Cltadd) ' If Self.accept (ClientID, client): ClientID = ClientiD + 1 # Connect Thread class, this class was use for connecting with client and receiving client ' s message Class Serverconn Ectthread (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.disconnect = Disconnect Self.clientname = None self.inputs = self.client.makefile (' RB ', 0) self.outputs = Self.client.makefile (' WB ', 0) def run (self): self.sendstring (' Input Your Name: ') while True: string = Self.readline () If string:string = String.lstrip () If Len (string) >0:SELF.R Eceive (self, string) Else:self.inputs.close () Self.outputs.close () break if self.client Name:self.disconnect (self) def sendstring (Self, string): Self.sendbytes (Bytes (string, self.encoding)) def s Endbytes (Self, BTS): Self.outPuts.write (BTS) def readline (self): rec = self.inputs.readline () If rec:string = Bytes.decode (REC, SELF.E ncoding) If Len (string) >2:string = string[0:-2] else:string = "else:string = False return String # Chat Class Server class, this is constitute of a listen thread and many connect thread cl Chatroomserver:def __init__ (self, ip= ' 0.0.0.0 ', port=9113, encoding= ' Utf-8 '): self.hostname = IP self.encod ing = encoding Self.port = Port self.clients = {} Self.clientnames = {} def whenconnect (self, ClientID, Clie NT): Log (' A connect with id=%s%s '% ('%d Address: '%clientid, Client.getpeername ())) ' Connect = Serverconnectthread (c Lientid, client, self.encoding, self.whenreceive, Self.whenexit) Connect.start () return True def whenreceive (SE LF, 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 = Datetime.datetime.now () sendstring = '%s%s ' \ r \ n%s\r\n '% (now, Client.clientname, String) Self.sendtoall (sendstring, client) else:if Self.clientnam Es.__contains__ (String): Client.sendstring ('%s is exited!!! \ r \ n '%string) Else:client.clientname = string client.sendstring (' Hell,%s!!! \ r \ n '%client.clientname) self.addclient (client) return True def whenexit (self, client): Self.delclient (c Lient) return True def handlecmd (self, client, cmd): Log (' cmd:%s '%cmd) if cmd== ' user ': Client.sendstr ing (' User list (%d): \ r \ n '%len (self.clients)) for i in SELF.CLIENTS:CLT = Self.clients[i] Client.send String ('%d\t%s\r\n '% (Clt.clientid, clt.clientname)) else:client.sendstring (' unknow command:%s:\r\n '%cmd) de F Start (self): Serverlisten = Serverlistenthread (Self.hostname, Self.port, Self.whenconnect) sErverlisten.start () def sendtoall (self, string, notfor): Sends = bytes (string, self.encoding) for I in Self.clie Nts:if not (Notfor and notfor.clientid==i): Self.clients[i].sendbytes (Sends) def addclient (self, client): Self.sendtoall ('%s logined!!! \ r \ n '%client.clientname, client) Self.clients[client.clientid] = client Self.clientnames[client.clientname] = Clie Nt.clientid def delclient (self, client): Self.sendtoall ('%s logouted!!! \ r \ n '%client.clientname, client) del Self.clients[client.clientid] del Self.clientnames[client.clientname] # start A chat Class Server Chatroomserver (). Start ()
With this server program will be able to (of course, if you install the Python interpreter), no client, then you will ask how to start chatting?
Here's how to start chatting, first you run the file, as you can see the server is waiting for the client to log on:
The client logs in directly using the Telnet command, noting that the port should be the same as the server, with the command: Telnet 127.0.0.1 9011, automatically open the Telnet console, enter your name:
Now you look at the server-side console interface and you can see the logged in message:
Continue using Telnet to log in to another user and then 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.
Hopefully this article will help you with Python programming.