Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【实践相关】Vue + Koa2 + Socket.io #42

Open
guapi233 opened this issue Nov 23, 2020 · 0 comments
Open

【实践相关】Vue + Koa2 + Socket.io #42

guapi233 opened this issue Nov 23, 2020 · 0 comments
Labels
工具库使用 对工具库的使用经验

Comments

@guapi233
Copy link
Owner

Vue + Koa2 + Socket.io

依赖库版本信息

  • vue:2.6.11

  • koa:2.7.0

  • socket.io:3.03

  • socket.io-client:3.03

Koa2集成

const Koa = require('koa');
const app = new Koa();
const server = require('http').Server(app.callback());
const io = require('socket.io')(server);
const port = 8081;

server.listen(process.env.PORT || port, () => {
     console.log(`app run at : http://127.0.0.1:${port}`);
})

io.on('connection', socket => {
     console.log('初始化成功!下面可以用socket绑定事件和触发事件了');
     socket.on('send', data => {
          console.log('客户端发送的内容:', data);
          socket.emit('getMsg', '我是返回的消息... ...');
     })

     setTimeout( () => {
         socket.emit('getMsg', '我是初始化3s后的返回消息... ...') 
     }, 3000)
})

如果是在不同源下进行socket连接,需要,在创建io实例时将配置项cors打开:

io = io(server, { cors: true });

Vue集成

如果想在组件内部使用socket实例 ,可以使用vue-socket.io,我是将socket实例绑定在vuex上,所以只需安装官网要求的socket.io-client即可。

import config from "@/config";
import { io } from "socket.io-client";

const socket = io(config.baseUrl);

socket.on("connect", () => {
  console.log("???");
});

export default socket;
@guapi233 guapi233 added the 工具库使用 对工具库的使用经验 label Nov 23, 2020
@guapi233 guapi233 changed the title Vue + Koa2 + Socket.io 【实践相关】Vue + Koa2 + Socket.io Nov 23, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
工具库使用 对工具库的使用经验
Projects
None yet
Development

No branches or pull requests

1 participant