Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

python开发一个简单的聊天室

$
0
0
python开发一个简单的聊天室

一点号Python热爱者昨天

使用python的twisted框架编写一个简单的聊天室

下面是基本架构


php?url=0FM28hA4gZ" alt="python开发一个简单的聊天室" />

基本架构图

# -*- coding:utf-8 -*-

fromtwisted.internet.protocolimportFactory

fromtwisted.protocols.basicimportLineReceiver

fromtwisted.internetimportreactor

user = {}

classChatReci(LineReceiver): #定义一个类,这里继承的是LineReceiver

def__init__(self): #初始化2个变量

self.name =''

self.state ="game"

defconnectionMade(self): #连接协议,当客户端连接即发出消息

self.sendLine("input you name?")

deflineReceived(self, data): #这个函数定义了取名 打印欢迎界面,以及发送信息给连上来的用户

ifself.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) #定义聊天信息

forur,protocolinuser.items: #取他的用户名

ifprotocol != user: #判断他是不是一个用户 如果不是就传送消息

protocol.sendLine(message) #传送消息

factory = Factory #定义工厂

factory.protocol = ChatReci #绑定我的类

reactor.listenTCP(22222, factory) #绑定端口和工厂

reactor.run #启动

效果图:


python开发一个简单的聊天室

效果图1


python开发一个简单的聊天室

效果图2

喜欢python的朋友可以加群330637182 让我们共同学习进步


Viewing all articles
Browse latest Browse all 9596

Trending Articles