python多人聊天程序程序代码_python的多人多功能聊天室

这篇博客介绍了一个基于Twisted库构建的Python多人聊天程序。程序包括多人聊天室和私聊功能,用户可以使用命令如'/login'、'/who'、'/look'、'/to'等进行交互。博客提供了详细的代码实现,并展示了启动聊天服务器的日志输出。
摘要由CSDN通过智能技术生成

从Beginning Python: From Novice to Professional, Second Edition 中的一个chatroom项目中拿出来的。那里的聊天室,只有一个单间聊天室功能,使用asyncore和asynchat实现,只能群聊。后来我给它加上了多人聊天室功能。还加上了私聊等功能。改用twisted实现并把它变成了守护模式(使用twistd)

命令列表:

/login username [roomname]

/who 查看当前登录的用户

/look 查看在当前聊天房间的用户

/to username content 私信用户

/exit 退出当前聊天房间

/logout 退出聊天服务器

代码如下:

from twisted.internet import reactor

from twisted.internet.protocol import Protocol,Factory

from twisted.internet import defer

from twisted.protocols.basic import LineReceiver

from twisted.application import internet,service

from twisted.python import log

class commaneHandler:

def handle(self,session,line):

if not line.strip():return

parts=line.split(' ',1)

cmd=parts[0].strip()

try:

if cmd[0]!='/':

cmd="/say"

line=line.strip()

else:

line=parts[1].strip()

except IndexError:

line=""

finally:

cmd=cmd[1:].strip()

meth=getattr(self,"do_"+cmd,None)

try:

meth(session,line)

except TypeError:

self.unknow(session,cmd)

def unknow(self,session,cmd):

session.write("%s:unknow command!\n"%cmd)

cla

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值