SocketIO

下载socket.io.js

$this.SocketIO = {
            client: null,
            create: function (host, port, ready) {
                let _client = {};
                _client.host = host;
                _client.port = port;
                // _client.socket = io('http://' + host + ':' + port);
                _client.socket = io('http://' + host + ':' + port);
                _client.socket.on('connect', () => {
                    console.log("连接成功", _client.socket.id);
                    this.login();
                    if (ready) ready();
                });
                _client.socket.on('connect_error', (error) => {
                    console.error("连接错误");
                });
                _client.socket.on('connect_timeout', (timeout) => {
                    console.log("连接超时");
                });
                _client.socket.on('error', (error) => {
                });
                _client.socket.on('disconnect', (reason) => {
                    console.log("关闭连接");
                });
                _client.socket.on('reconnect', (attemptNumber) => {
                    console.log("重新连接");
                });
                _client.socket.on('reconnect_error', (error) => {
                });
                _client.socket.on('reconnect_failed', () => {
                });
                _client.socket.on('ping', () => {
                    //console.log("向服务器端发送数据包");
                });
                _client.socket.on('pong', (latency) => {
                    //console.log("接收服务器数据包");
                });
                _client.send = (event, msg, callback) => {
                    if (callback) {
                        _client.socket.emit(event, msg, (data) => callback);
                    } else {
                        _client.socket.emit(event, msg);
                    }
                }
                _client.receive = (event, callback) => {
                    _client.socket.on(event, callback);
                }
                this.client = _client;
                return this.client;
            },
            login: function () {
                if ($this.session.get('USER')) {
                    this.client.send('login', $this.session.get('USER').id);
                }
            },
            logout: function () {
                this.client.send('logout', $this.session.get('USER').id);
            }
        };
app.vue里全局监听
this.SocketIO.create('192.168.1.120', 9098);
this.SocketIO.client.receive('service_message', (data) => {
     window.dispatchEvent(new CustomEvent('cargo_trace', {detail:data}));
});
window.addEventListener('cargo_trace', (event)=>{})

service_message 与后端约好的名
cargo_trace 自定义监听的方法名

你可能感兴趣的:(SocketIO)