搜索文档
服务流程
- 客户端发送消息
- 服务器接收消息
- 服务器广播消息
- 客户端接收广播
服务端
安装 express
sh
npm i express安装 socket.io
sh
npm i socket.io创建入口文件 index.js
js
const express = require('express')
const app = express()
const port = 3000
const { Server } = require("socket.io");
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
// 创建 io 对象
const io = new Server(4000, {});
io.on('connection', (socket) => {
console.log('socket 连接成功');
// 接收信息
socket.on('msg', data => {
/*
此时的 data 就是客户端发送的 msg 信息
接收到信息后通过 socket.broadcast.emit 广播出去
*/
socket.broadcast.emit('gb_msg', data);
})
})客户端
创建 uni-app 项目
使用 vue2 版本。
修改默认页面 pages/index/index.vue 代码,模拟会话窗口
html<template> <view class="page"> <view class="content"> <view class="record" v-for="(item, index) in record" :key="index">{{ item }}</view> </view> <view class="foot"> <input type="text" v-model="content" class="input" placeholder="请输入内容..."> <view class="btn" @click="send">发送</view> </view> </view> </template> <script> export default { data() { return { content: '', record: ['第一条消息', '第二条消息'] } }, methods: { // 发送消息 send() { let { content } = this; this.content = ''; console.log(content); } } } </script> <style lang="scss"> .page { width: 100vw; height: 100vh; .content { width: 100%; height: calc(100vh - 50px); background-color: white; padding: 25rpx; box-sizing: border-box; .record { line-height: 60rpx; border-bottom: 1rpx solid #eee; } } .foot { width: 100%; height: 50px; background-color: #f6f6f6; padding: 15rpx 25rpx; box-sizing: border-box; display: flex; align-items: center; justify-content: space-between; .input { width: 600rpx; height: 100%; padding: 0 10rpx; box-sizing: border-box; border-radius: 4rpx; background-color: white; } .btn { width: 80rpx; height: 30px; text-align: center; line-height: 30px; border-radius: 6rpx; color: white; background-color: $uni-color-primary; } } } </style>
安装 weapp.socket.io
安装
shnpm i weapp.socket.io在
main.js文件中weapp.socket.io并创建全局变量$socketjsimport App from './App' import io from 'weapp.socket.io' import Vue from 'vue' import './uni.promisify.adaptor' Vue.config.productionTip = false App.mpType = 'app' Vue.prototype.$socket = io('http://127.0.0.1:4000'); const app = new Vue({ ...App }) app.$mount()
发送与就收消息
修改 index.vue 文件
js
methods: {
// 发送消息
send() {
let { content } = this;
if (content) {
this.record.push(content);
this.$socket.emit('msg', content);
this.content = '';
}
},
},
onLoad() {
// 接收信息
this.$socket.on('gb_msg', data => {
this.record.push(data);
})
}