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


Posted in Python onJune 17, 2015

本文实例讲述了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 相关文章推荐
python端口扫描系统实现方法
Nov 19 Python
Pyhton中防止SQL注入的方法
Feb 05 Python
浅析Python3爬虫登录模拟
Feb 07 Python
详解pandas的外部数据导入与常用方法
May 01 Python
Python中的十大图像处理工具(小结)
Jun 10 Python
Python搭建Spark分布式集群环境
Jul 05 Python
python读取ini配置的类封装代码实例
Jan 08 Python
解决Tensorboard 不显示计算图graph的问题
Feb 15 Python
python属于软件吗
Jun 18 Python
python speech模块的使用方法
Sep 09 Python
使用pytorch实现线性回归
Apr 11 Python
Pandas||过滤缺失数据||pd.dropna()函数的用法说明
May 14 Python
Python使用urllib2模块实现断点续传下载的方法
Jun 17 #Python
Python合并两个字典的常用方法与效率比较
Jun 17 #Python
Python操作串口的方法
Jun 17 #Python
Python求两个文本文件以行为单位的交集、并集与差集的方法
Jun 17 #Python
Django中模型Model添加JSON类型字段的方法
Jun 17 #Python
Python中map和列表推导效率比较实例分析
Jun 17 #Python
wxPython使用系统剪切板的方法
Jun 16 #Python
You might like
一键删除顽固的空文件夹 软件下载
2007/01/26 PHP
PHP数组 为文章加关键字连接 文章内容自动加链接
2011/12/29 PHP
php接口与接口引用的深入解析
2013/08/09 PHP
php中filter_input函数用法分析
2014/11/15 PHP
CodeIgniter与PHP5.6的兼容问题
2015/07/16 PHP
php 删除指定文件夹的实例讲解
2017/07/25 PHP
php数据库的增删改查 php与javascript之间的交互
2017/08/31 PHP
PHP封装的XML简单操作类完整实例
2017/11/13 PHP
php-msf源码详解
2017/12/25 PHP
解决PHPstudy Apache无法启动的问题【亲测有效】
2020/10/30 PHP
浅析Node.js查找字符串功能
2014/09/03 Javascript
JavaScript Math 对象常用方法总结
2016/04/28 Javascript
jquery根据td给相同tr下其他td赋值的实现方法
2016/10/05 Javascript
原生JS实现图片轮播切换效果
2016/12/15 Javascript
Node.js如何响应Ajax的POST请求并且保存为JSON文件详解
2017/03/10 Javascript
深入理解Vue transition源码分析
2017/07/30 Javascript
浅谈Vue SPA 首屏加载优化实践
2017/12/15 Javascript
jQuery操作attr、prop、val()/text()/html()、class属性
2019/05/23 jQuery
vue.js+elementUI实现点击左右箭头切换头像功能(类似轮播图效果)
2019/09/05 Javascript
Python实现配置文件备份的方法
2015/07/30 Python
使用Python进行AES加密和解密的示例代码
2018/02/02 Python
Python数据分析之获取双色球历史信息的方法示例
2018/02/03 Python
Python中浅拷贝copy与深拷贝deepcopy的简单理解
2018/10/26 Python
python基于property()函数定义属性
2020/01/22 Python
jupyter notebook 调用环境中的Keras或者pytorch教程
2020/04/14 Python
解决使用Pandas 读取超过65536行的Excel文件问题
2020/11/10 Python
python元组拆包实现方法
2021/02/28 Python
雅诗兰黛旗下专业男士保养领导品牌:Lab Series
2017/05/15 全球购物
软件测试常见笔试题
2012/02/04 面试题
军训个人总结
2015/03/03 职场文书
南京大屠杀观后感
2015/06/02 职场文书
2016孝老爱亲模范事迹材料
2016/02/26 职场文书
党员学习型组织心得体会
2019/06/21 职场文书
Vue.js中v-for指令的用法介绍
2022/03/13 Vue.js
python使用opencv对图像添加噪声(高斯/椒盐/泊松/斑点)
2022/04/06 Python
Golang连接并操作MySQL
2022/04/14 MySQL