不为别的,只为做一个连自己都羡慕的人

python-socketio实现websocket的连接与使用

版本要求:

 python-socketio 5.1.0
 python-engineio  4.3.1

服务端代码:

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实现长链接):

版本要求:"vue-socket.io": "^3.0.7"

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

 

posted @ 2022-04-01 13:43  升级打怪  阅读(2164)  评论(0编辑  收藏  举报