python基于twisted框架编写简单聊天室

yipeiwu_com6年前Python基础

本文实例为大家分享了使用python的twisted框架编写一个简单的聊天室具体代码,供大家参考,具体内容如下

下面是基本架构

代码:

# -*- coding:utf-8 -*-
from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
user = {}
class ChatReci(LineReceiver):    #定义一个类,这里继承的是LineReceiver
 def __init__(self):     #初始化2个变量
  self.name = ''
  self.state = "game"

 def connectionMade(self):      #连接协议,当客户端连接即发出消息
  self.sendLine("input you name?")

 def lineReceived(self, data):     #这个函数定义了取名 打印欢迎界面,以及发送信息给连上来的用户
  if self.name == '':      #判断名字是否为空 如果为空就进行下面的操作
   self.name = data      #给self.name赋值
   self.sendLine("you welcome, %s!" % (self.name))  #打印欢迎信息
   user[self.name] = self     #赋值给user
   print '%s loging' %data    #打印登录信息
  else:          #不为空就打印信息
   message = "<%s> %s" % (self.name, data) #定义聊天信息
   for ur,protocol in user.items():   #取他的用户名
    if protocol != user:     #判断他是不是一个用户 如果不是就传送消息
     protocol.sendLine(message)   #传送消息

factory = Factory()    #定义工厂
factory.protocol = ChatReci  #绑定我的类
reactor.listenTCP(22222, factory) #绑定端口和工厂
reactor.run()       #启动

效果图:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Django中Middleware中的函数详解

一个middleware的例子 import time from django.urls import reverse from django.utils.deprecation...

浅析Python 3 字符串中的 STR 和 Bytes 有什么区别

浅析Python 3 字符串中的 STR 和 Bytes 有什么区别

Python2的字符串有两种:str和Unicode,Python3的字符串也有两种:str和Bytes。Python2的str相当于Python3的Bytes,而Unicode相当于P...

Python清空文件并替换内容的实例

有个文本文件,需要替换里面的一个词,用python来完成,我是这样写的: def modify_text(): with open('test.txt', "r+") as f:...

python钉钉机器人运维脚本监控实例

python钉钉机器人运维脚本监控实例

如下所示: #!/usr/bin/python3 # -*- coding:UTF-8-*- # Author: zhuhongqiang from urllib impor...

Python不规范的日期字符串处理类

我分析了形如19920203、199203、1992.02.03、1992.02、1992-02-03、1992-02、920203时间格式特征,列出了正则表达式如下:复制代码 代码如下...