Python实现的使用telnet登陆聊天室实例

作者:RobinTang 时间:2023-11-17 10:41:17 

本文实例讲述了Python实现的使用telnet登陆聊天室。分享给大家供大家参考。具体如下:

前久在家学习Python的时候写的一个简单的聊天室,可以使用telnet来登陆。

遗憾的是现在对中文的支持很差,英文聊天倒是没什么问题了。

功能很简单的,应该没有你想象的那么强大,但是你如果有兴趣的话可以试试的。

另外,让我惊奇的是它可以在Android的平板上运行SL4A的Python解释器上运行(需要稍微改几句代码,貌似是编码的那个地方,我记不清了)。

现在这个是可以在PC上跑起来的。

废话不多,直接放代码了,就一个py文件而已,而且注释是乱七八糟的,编码风格也不好(好神似我在用类C语言的习惯)。


# Filename: ChatRoomServer.py
import threading
import datetime
import socket
# a simple log function
def log(lg):
 print(lg)
# Chat room server listen thread class, this class is use for listening client login
# when a client request to connect server, this class will 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_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 for 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 is use for connecting with client and 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.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.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.decode(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:'%clientid , 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 = datetime.datetime.now()
       sendstring = '%s %s\r\n %s\r\n'%(now, client.clientname, string)
       self.sendtoall(sendstring, client)
   else:
     if self.clientnames.__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(client)
   return True
 def handlecmd(self, client, cmd):
   log('cmd: %s'%cmd)
   if cmd=='user':
     client.sendstring('User list(%d):\r\n'%len(self.clients))
     for i in self.clients:
       clt = self.clients[i]
       client.sendstring(' %d\t%s\r\n'%(clt.clientid, clt.clientname))
   else:
     client.sendstring('Unknow command: %s:\r\n'%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 in self.clients:
     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] = client.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 room server
ChatRoomServer().start()

有了这个服务器程序之后就可以了(当然前提是你安装的Python解释器),没有客户端的,那么你会问怎么开始聊天呢?

下面开始介绍怎么开始聊天,首先你把这个文件运行起来,如下图可以看到服务器正在等待客户端登陆了:

Python实现的使用telnet登陆聊天室实例

客户端直接使用telnet命令登陆,注意端口应该和服务器的一样,命令为:telnet 127.0.0.1 9011,自动打开telnet控制台,输入自己的名字吧:

Python实现的使用telnet登陆聊天室实例

现在你在看看服务器端的控制台界面,可以看到记录了登陆消息:

Python实现的使用telnet登陆聊天室实例

继续使用telnet登陆另外的用户之后就可以聊天了:

Python实现的使用telnet登陆聊天室实例

功能很简陋了,不过这让我想起了二三十年前的事,嘿嘿,那时候应该就是这样子聊天的了吧,生在这个时代的我们永远都体会不到那种乐趣了。

希望本文所述对大家的Python程序设计有所帮助。

标签:Python,telnet,聊天室
0
投稿

猜你喜欢

  • python logging模块的使用总结

    2021-11-15 06:46:53
  • Window下Mysql忘记root密码怎么重置

    2024-01-15 22:33:23
  • Python和Go成为2019年最受欢迎的黑客工具(推荐)

    2021-05-22 16:37:17
  • python抓取百度首页的方法

    2023-05-25 13:31:58
  • Python中url标签使用知识点总结

    2022-05-12 11:13:09
  • select 终极美化

    2007-10-16 17:57:00
  • Pytorch 的 LSTM 模型的示例教程

    2021-08-01 22:28:41
  • Oracle SecureFile的功能第1/4页

    2009-06-19 18:07:00
  • Python Flask前端自动登录功能实现详解

    2021-12-13 17:36:17
  • node.js应用后台守护进程管理器Forever安装和使用实例

    2024-05-03 15:36:48
  • oracle 函数

    2010-07-23 13:06:00
  • CentOS7安装mysql5.7解压缩版简明教程

    2024-01-20 14:57:18
  • Python 实现数据结构-堆栈和队列的操作方法

    2021-05-25 20:56:16
  • Mysql联合查询UNION和UNION ALL的使用介绍

    2024-01-17 22:14:08
  • python实现监控windows服务并自动启动服务示例

    2021-01-19 01:30:13
  • django 装饰器 检测登录状态操作

    2021-03-13 16:40:40
  • position两三事

    2009-02-16 15:23:00
  • ASP+SQL Server构建网页防火墙

    2009-01-21 19:56:00
  • 不用mod_rewrite直接用php实现伪静态化页面代码

    2023-11-01 07:07:45
  • php自定义函数call_user_func和call_user_func_array详解

    2024-05-11 10:09:11
  • asp之家 网络编程 m.aspxhome.com