2017-06-01 83 views
0

我正在嘗試創建一個類似於應用程序的FB聊天。我已經開始了最低限度的瓶塞實施。到目前爲止,我已經知道客戶端和服務器端通過一個通用處理程序進行通信。我目前的實施是免費的所有聊天。爲了簡便起見,我只是顯示處理程序:Flask socketio多個連接

客戶端:

socket.on('message', function(msg) { 
    $("#messages").append('<li>'+msg+'</li>'); 
    console.log('Received message'); 
}); 

服務器端:

@socketio.on('message') 
def handleMessage(msg): 
print('Message: ' + msg) 
send(msg, broadcast=True) 

問:

如何傳遞參數,以便我可以有不同的聊天ID

回答

0

我想你想要做的是一些聊天室。好消息! Flask-SocketIO現在正在處理房間。 可以導入模塊是這樣的:

from flask_socketio import SocketIO, emit, join_room, leave_room, 
close_room, rooms, disconnect 

對於加入一個房間,它看起來像這樣:

@socketio.on('join', namespace='/test') 
def join(message): 
    join_room(message['room']) 
    session['receive_count'] = session.get('receive_count', 0) + 1 
    emit('my_response', 
     {'data': 'In rooms: ' + ', '.join(rooms()), 
'count': session['receive_count']}) 

您可以找到Miguel's Github page :)

0

的代碼一個完整的例子嗨,以前的回答很抱歉。 您可以從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,但你可以實現我的代碼。

相關問題