的代碼一個完整的例子嗨,以前的回答很抱歉。 您可以從sid獲取cookie。如果您將聊天ID保存到Cookie中。您可以輕鬆識別用戶標識。 這是我的命名空間代碼。
import socketio
import imp
import json
from datetime import datetime, timedelta
gameDBModule = imp.load_compiled("ChatDatabase", "./game_chat/chat_database.pyc")
apiModule = imp.load_compiled("TotoAPI", "./game_api/__init__.pyc")
class GameChat(socketio.Namespace):
def init(self):
self.lastDataIndex = 0
self.api = apiModule.TotoAPI()
def on_join(self, sid, message):
self.db = gameDBModule.ChatDatabase()
sessid = self.getUserId(sid)
try:
info = json.loads(self.api.userinfo(sessid))
userID = str(info[4])
except Exception as e:
userID = None
self.emit('join', {'history': self.db.get_chathistory(), 'channel': message, 'moderator': False, 'user_id': userID}, room=sid)
def on_connect(self, sid, environ):
self.emit('connect', {'data': 'Connected', 'count': 0}, room=sid)
print('GameChat Connected')
def on_say(self, sid, message, environ):
sessid =self.getUserId(sid)
try:
info = json.loads(self.api.userinfo(sessid))
userID = str(info[4])
except Exception as e:
userID = None
if userID !=None:
userID = None
#Save into History
now = self.get_current_time(9)
self.lastDataIndex = self.lastDataIndex + 1
item = {
'dataIndex': self.lastDataIndex,
'bot': False,
'date': now,
'message': message,
'role': 'user',
'type': 'say',
'user_id': userID
}
self.emit('msg', item)
item['date'] = self.get_current_time(0)
self.db.insert_chatting(item)
def on_disconnect(self, sid):
print('GameChat disconnected')
def getUserId(self, sid):
try:
#Get UserID from Cookies
cookies = str(self.server.environ[sid]['HTTP_COOKIE']).split(';')
id = None
for item in (cookies):
name=str(item).split('=')[0].strip()
value=str(item).split('=')[1].strip()
if name.__eq__('ci_session'):
id = value
return id
except Exception as e:
return None
def get_current_time(self, diff):
i = datetime.now() - timedelta(hours = diff)
return i.isoformat()[:-3]+"Z"
this is the code using above name space
async_mode = 'eventlet'
import eventlet
import eventlet.wsgi
from flask import Flask, render_template, Response, request, make_response
import socketio
import imp
gameChatModule = imp.load_compiled("GameChat", "./game_chat/__init__.pyc")
apiModule = imp.load_compiled("TotoAPI", "./game_api/__init__.pyc")
sio = socketio.Server(logger=False, async_mode=async_mode)
app = Flask(__name__)
app.wsgi_app = socketio.Middleware(sio, app.wsgi_app)
app.config['SECRET_KEY'] = 'secret!'
api = apiModule.TotoAPI()
ns = gameChatModule.GameChat("/")
ns.init()
if __name__ == '__main__':
sio.register_namespace(ns)
eventlet.wsgi.server(eventlet.listen(('', 8880)), app)
我已經在python 2.7中實現它你似乎使用python 3,但你可以實現我的代碼。