短视频程序源码,实现一个简单的websocket
实现简单的websocket,只需要几步:
1、引入socket.io组件;
2、前端初始化页面时,监听socket.on(‘chatMsg’, () => xxx);
3、需要发送事件时,触发socket.emit(‘chatMsg’, ‘msg’);
4、后端监听事件并回调即可
index.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><divid="app"><inputtype="text"id="name"><buttontype="button"@click="submit">send</button><ul v-for="(item, i) in msgList":key="item + new Date().getTime()"><li>{{i+1}}.{{item}}</li></ul></div><scriptsrc="https://cdn.bootcdn.net/ajax/libs/axios/0.21.0/axios.js"></script><scriptsrc="https://lib.baomitu.com/vue/2.6.12/vue.js"></script><scriptsrc="https://lib.baomitu.com/socket.io/3.0.1/socket.io.js"></script><script>// 生成对象letsocket=io();letvm=newVue({el:'#app',data:{msgList:[],},created(){// 监听socket.on('chatMsg',(msg)=>{vm.msgList.push(msg)})},methods:{submit:async()=>{letmsg=document.getElementById('name').value;document.getElementById('name').value='';// 发送事件socket.emit('chatMsg',msg);},}})</script></body></html>index.js
constexpress=require('express');constapp=express();consthttp=require('http').Server(app);constio=require('socket.io')(http);app.get('/',(req,res)=>{res.sendFile(__dirname+'/index.html');})// 监听io.on('connection',(socket)=>{console.log('a socket connection....');// 事件到达时socket.on('chatMsg',(msg)=>{io.emit('chatMsg',msg);})// 链接断开时socket.on('disconnect',()=>{console.log('disconnect');})})http.listen(3000,()=>{console.log('http listen3000............');})以上就是短视频程序源码,实现一个简单的websocket, 更多内容欢迎关注之后的文章