1. 程式人生 > 其它 >python-socketio實現websocket的連線與使用 vue使用vue-socket.io實現長連結

python-socketio實現websocket的連線與使用 vue使用vue-socket.io實現長連結

服務端程式碼:

import socketio
import tornado.web
sio = socketio.AsyncServer(async_mode='tornado', logger=True, engineio_logger=True, cors_allowed_origins='*')

name_space = '/news'

client_query = []


# 列表字典去重
def list_dict_duplicate_removal(data_list):
    from functools import reduce
    def run_function(x, y): 
return x if y in x else x + [y] return reduce(run_function, [[], ] + data_list) @sio.on("connect", namespace=name_space) async def connect(sid, nversion, auth=1): print(f'connected sid={sid}') # await sio.emit('hello', (1, 2, {'hello': 'you'}), to=sid) print("給客戶端傳送訊息。。。。。。")
await sio.emit('message', 'calling control', broadcast=False, namespace=name_space, room=sid) print('有新連線,id=%s接加入' % (sid)) @sio.on("message", namespace=name_space) async def my_message(sid, message): print(my_message) print(message) print(type(message)) # emit('my_response_message
', message, broadcast=True, namespace=name_space) import json try: dd = json.loads(json.dumps(message)) print(dd["socketid"]) if dd.get("socketid") is not None: client_query.append(dd) except Exception as err: print(err) try: client_query1 = list_dict_duplicate_removal(client_query) d = json.loads(message) if d.get("userId") is not None: for key in client_query1: if key["userid"] == d["userId"]: await sio.emit(d["userId"], message, broadcast=False, namespace=name_space, room=key["socketid"]) # emit("my_response_message", message, broadcast=False, namespace=name_space,room=d["userId"]) if d.get("approvalId") is not None: for key in client_query1: if key["userid"] == d["approvalId"]: print("*************") await sio.emit(d["approvalId"], message, broadcast=False, namespace=name_space, room=key["socketid"]) # emit("my_response_message", message, broadcast=False, namespace=name_space,room=d["approvalId"]) except Exception as err: print(err) @sio.on("disconnect", namespace=name_space) def disconnect(sid): try: client_query.remove(sid) except Exception as err: print(err) print('有連線,id=%s接退出, 當前連線數%d' % (sid, len(client_query))) class MainHandler(tornado.web.RequestHandler): def get(self): self.render("index.html") if __name__ == "__main__": # 載入檔案設定 settings = { 'debug': True, 'static_path': os.path.join(os.path.dirname(__file__), "static"), 'template_path': os.path.join(os.path.dirname(__file__), "template"), } # 配置路由 application = tornado.web.Application([ # 頁面中路由配置 (r"/", MainHandler), ], **settings) application.listen(4321) tornado.ioloop.IOLoop.instance().start()

python實現客戶端程式碼:

import json

from time import sleep
import socketio

sio = socketio.Client()


@sio.on('disconnect', namespace='/news')
def disconnect():
    print('disconnect ', sio.sid)


@sio.on('connect', namespace='/news')
def on_connect():
    print("I'm connected to the /news namespace!")


def entry(n):
    print('listen task channel')
    sio.connect('http://127.0.0.1:4321/news')
    sio.emit('message', n, namespace='/news')
    print("訊息傳送成功!")
    # 訊息結束之後,斷開連線(不呼叫鍛鍊開連線,則會一直掛起!)
    # sio.wait()
    sleep(5)
    sio.disconnect()


if __name__ == '__main__':
    n = {"code": 1, "message": "success", "userId": "10", "approvalId": "10"}
    entry(json.dumps(n))

vue實現客戶端程式碼(vue使用vue-socket.io實現長連結):

1.下載

npm install vue-socket.io --save

2.在main.js中引入

import VueSocketIO from "vue-socket.io";
import SocketIO from "socket.io-client";
Vue.prototype.SocketIO = SocketIO;

3.獲取連結地址並在main.js裡面匯入 

const baseSocket = 'http://8.8.8.8:8080'  Vue.prototype.socketApi = baseSocket
Vue.use(new VueSocketio({
    debug: true,
    connection: SocketIO.connect(baseSocket, {
        path: '',
        transports: ['websocket', 'xhr-polling', 'jsonp-polling'],
    })
}));

4.在元件中使用

this.socket = this.SocketIO(this.socketApi);
this.socket.on("connect", datas => {
            this.socket.emit("login", this.info.id);
            this.socket.on("daymarket", data => {
                 console.log(data)
            });
          });
//其中socket 可以在data裡面定義
//connect和login和daymarket都是後臺定義的名字,this.info.id根據後臺要求傳的id

5.銷燬

this.socket.disconnect()

轉載於:https://www.cnblogs.com/wu-hen/p/13246084.html