xmpppy + openfire

本文探讨了如何将XMPP服务器和Mysql数据库应用于在线聊天系统,并提供了与自有项目的整合案例,包括消息处理、状态更新及多用户对话的实现。
最近公司有个在线聊天的需求,最新看了一下xmpp
Server 使用的事OpenFire 数据库使用的事Mysql
功能到时齐全,但是,跟自有项目的整合就成了问题,有一些需求实现不了,下面是个实验的例子,仅供参考 :)

#coding=utf-8
""" notgen.py """

import sys, os
import xmpp
import time
import string
from threading import Thread

ROOM = ''
LOGGING = 1


#utility functions
def buildTrans():
"""
create a translation table using string.maketrans to help remove unwanted
chars from the sql string to output. If a char is not in the set 'printable'
translate it to a space.
"""
dl = ''
sl = ''
for i in range(256):
c = chr(i)
if c not in string.printable:
dl = dl + c
sl = sl + ' '
return string.maketrans(dl, sl)

#global translate table built from above function...used to remove
#unwanted chars from sql record output.
TTABLE = buildTrans()


def messageCB(conn, msg):
mt = msg.getType()
mgf = msg.getFrom()
mb = msg.getBody()
try:
msg = msg.encode("utf-8")
except:
pass

if mt == 'groupchat':
print mgf + ': ' + mb
if mt == 'chat':
print "\033[1m\033[36m %s say: %s\033[0m" % ( mgf, mb)
print


def presenceCB(conn, msg):
""""
Please note: this function is a call back invoked when a 'presence' type
packet is received. I put a try/except around the code...as we were getting
unicode errors from some source..in the print statement. Did not want to take
the time to troubleshoot further for now.
"""
try:
print "presence msg rec'd: ", msg
prs_type = msg.getType()
who = msg.getFrom()
if prs_type == "subscribe":
conn.send(xmpp.Presence(to=who, typ='subscribed'))
conn.send(xmpp.Presence(to=who, typ='subscribe'))
except Exception, e:
print e
print 'exception in presenceCB...ignoring'


class gChat(Thread):
""" to hold data and methods for doing group chat """

def __init__(self, room=ROOM, jid="edisonlz@localhost", pwd="wwwwww"):
"""set up connection and etc."""
Thread.__init__(self)
self.flag = True
self.pwds = pwd
self.rooms = room
self.jids = jid

def run(self):
self.mainloop()

def stop(self):
self.flag = False


def setupConn(self):
""" set up the IM Connection """
self.jid = xmpp.protocol.JID(self.jids)
self.cl = xmpp.Client(self.jid.getDomain(), debug=None)
self.cl.connect()
self.cl.auth(self.jid.getNode(), self.pwds)

self.cl.sendInitPresence()
self.cl.sendPresence(typ='Available')

self.cl.RegisterHandler('message', messageCB)
self.cl.RegisterHandler('presence', presenceCB)

self.room = self.rooms
if self.room:
self.cl.send(xmpp.Presence(to=self.room, status='Available'))

def StepOn(self):
try:
self.cl.Process(1)
except KeyboardInterrupt:
return 0
time.sleep(1)
return 1

def sendAvailable(self):
""" send Available presence """
self.cl.send(xmpp.Presence(to=self.room, status='Available'))

def sendMsg(self, msg):
msg = msg.translate(TTABLE) #REMOVE unwanted chars
msg = xmpp.protocol.Message(body=msg, typ="chat", to='shaols@localhost', frm='edisonlz@localhost')
mid = self.cl.send(msg)
print 'message sent with mid: ', `mid`
time.sleep(1)


def mainloop(self):
""" main loop for this groupchat session """
while self.flag:
self.setupConn()
ct = 0
while self.StepOn():
if ct > 60:
self.sendAvailable()
ct = 0


class gTalk(Thread):
def __init__(self, gc):
Thread.__init__(self)
self.flag = True
self.gc = gc

def run(self):
while self.flag:
data = raw_input("\033[1m\033[33m\033[42mchat: \033[0m")
if data:
if data == "exit":
self.stop()
self.gc.stop()
exit(1)
print "exit......."

try:
self.gc.sendMsg(data.decode("utf-8"))
except Exception, e:
self.gc.sendMsg(data)
print

time.sleep(0.1)

def stop(self):
self.flag = False


def main():
gc = gChat()
gt = gTalk(gc)
try:
print "[run chat]"
gc.start()
print "[run talk]"
gt.start()
except KeyboardInterrupt:
gc.stop()
gt.stop()
except Exception, e:
gc.stop()
gt.stop()


if __name__ == '__main__':
main()
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值