一、koa结合socket.io
后端代码:
// 引入依赖
const koa = require("koa");
// 初始化koa
const app = new koa();
// 开启 http
var server = require("http").createServer(app.callback());
// 初始化 socket
const io = require("socket.io")(server, { cors: true });
// 监听
io.on("connection", (socket) => {console.log("有人链接");//接收数据socket.on('send', function (data) {console.log(data);// 发送数据socket.emit('resend', {msg: `你好${data.msg}`,code: 200});});
});
server.listen(3000);
前端代码:
<template><div class="hello"><input type="text" v-model="msg"><button @click="sendMsg">发送</button></div>
</template><script>
import io from 'socket.io-client'
export default {name: 'HelloWorld',data () {return {msg: 'Welcome to Your Vue.js App'}},mounted () {const socket = io('ws://localhost:3000')this.socket = socketwindow.socket = socketsocket.on('connect', function () {console.log('连接建立成功了!')})socket.on('disconnect', function () {console.log('断开连接了')})socket.on('resend', function (data) {console.log(data)})},methods: {sendMsg () {// 发送信息给服务端this.socket.emit('send', {msg: this.msg})}}
}
</script>
<style scoped></style>
二、express 结合 socket.io
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http, { cors: true });app.get('/', function(req, res){res.send('<h1>你好web秀</h1>');
});io.on('connection',function(socket) {console.log("有人链接");//接收数据socket.on('send', function (data) {console.log(data);// 发送数据socket.emit('resend', {msg: `你好${data.msg}`,code: 200});});
});http.listen(3000, function(){console.log('listening on *:3000');
});
前端代码:
<template><div class="hello"><input type="text" v-model="msg"><button @click="sendMsg">发送</button></div>
</template><script>
import io from 'socket.io-client'
export default {name: 'HelloWorld',data () {return {msg: 'Welcome to Your Vue.js App'}},mounted () {const socket = io('ws://localhost:3000')this.socket = socketwindow.socket = socketsocket.on('connect', function () {console.log('连接建立成功了!')})socket.on('disconnect', function () {console.log('断开连接了')})socket.on('resend', function (data) {console.log(data)})},methods: {sendMsg () {// 发送信息给服务端this.socket.emit('send', {msg: this.msg})}}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped></style>
注意:
如果出现跨域报错,可以参考以下解决方案:
- 重装socket.io-client
npm i socket.io-client --save
- 在vue中使用