vue2如何正确使用socket.io

1,341 阅读1分钟

先创建一个项目,然后

npm install express socket.io

npm init webpack vuesocketdemo

npm install vue-socket.io

npm install socket.io-client

把需要的依赖先装上

然后在assets/js里新建一个websocket.js

const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const app = express();
const server = http.createServer(app);

const io = socketIO(server, {
  cors: {
    origin: '*'
  }
});

io.on('connection', (socket) => {
  console.log('user connected');
  socket.on('hello', (data) => {
    console.log(`收到客户端的消息:${data}`);
  })
});


app.get('/', (request, response) => {
  /*在浏览器发送 http://127.0.0.1:24000 的请求,客户端定义了监听'message'的socket,所以可以接收消息,即使客户端有代码
      io.on('message',(data) => {
          console.log(data);
      });
  */
  io.emit('message', '服务端向客户端推送消息...');
  response.writeHead(200, { "Content-type": "text/plain" });
  response.end();
});


// 监听3000的端口
server.listen(3000, () => {
  console.log("server is up and running on port 3000");
});

配置一下端口号这些

然后在main.js里引入和配置

import VueSocketIO from 'vue-socket.io'
import SocketIO from 'socket.io-client'

Vue.use(new VueSocketIO({
  debug: true,
  // 这里的端口号要和你之前在websocket.js里配置的端口号相同
  connection: SocketIO('ws://localhost:3000')
}));

配置完成之后在需要用到的页面

import io from 'socket.io-client'
const socket = io('http://localhost:3000')

引入io还有定义socket常量

然后在页面加一个按钮点击发送一个hellow并且打印出来

socket.emit('hello', console.log('hellow'))

运行

image.png

可以看到控制台提示连接成功并且打印出来hellow,说明成功了~