装包:
yarn add socket.io
node后台:
const express = require('express')
const http = require('http')
const socket = require('socket.io')
const { getUserInfoByToken } = require('../../utils/light/tools')let app = express()
const server = http.createServer(app)
const io = socket(server, {cors: {origin: ['http://localhost:3000','https://xutongbao.top','https://chat.xutongbao.top',],},
})io.on('connection', async (socket) => {console.log('已连接', socket.id)//测试socket.on('/socket/test', async (data) => {console.log('data', data)io.sockets.emit('/socket/test', data)const ids = await io.allSockets()console.log(ids)})//登录socket.on('/socket/login', async (req) => {const ids = await io.allSockets()let user = await getUserInfoByToken(req.headers.authorization)global.onlineUsers.push({socketId: socket.id,userId: user.uid,nickname: user.nickname,})global.onlineUsers = global.onlineUsers.filter((item) => [...ids].includes(item.socketId)).filter((item) => item.userId)console.log(global.onlineUsers)console.log('在线人数', global.onlineUsers.length)io.sockets.emit('/socket/login', req)})
})server.listen(84, (res) => {console.log('socket', 84, res)
})module.exports = {io,
}
前端装包:
yarn add socket.io-client
前端代码:
import { io } from 'socket.io-client'
import { socketBaseURL } from '../utils/config'const socket = io(`${socketBaseURL}`)function onConnect() {console.log('登录,已连接', socket.id)
}
socket.on('connect', onConnect)socket.on('/socket/login', (res) => {console.log(res)
})const handleLogin = () => {let config = {headers: {},}if (config.isNotNeedToken !== true) {config.headers.authorization = localStorage.getItem('token')}if (window.platform === 'rn') {config.headers.platformos = localStorage.getItem('platformos')? localStorage.getItem('platformos'): 'rn'config.headers.version = localStorage.getItem('appVersion')? localStorage.getItem('appVersion'): ''} else {config.headers.platformos = 'h5'config.headers.version = window.version}config.headers.href = `${document.location.href}?platformos=${config.headers.platformos}&version=${config.headers.version}`socket.emit('/socket/login', {...config,code: 200,data: {},message: '成功',time: Date.now(),})
}export { socket, handleLogin }
const socketBaseURL = {// 使用反向代理解决跨域时,dev应为空字符串//dev: '',dev: 'http://172.20.10.4:84', //192.168.0.137 localhost 192.168.1.107 172.20.10.4:84//dev: 'http://yuying-api.xutongbao.top',test: '',//prod: 'http://yuying-api.xutongbao.top',prod: '' //使用nginx代理解决https请求转发到http
}[process.env.REACT_APP_MODE]export { socketBaseURL }
nginx配置:
server {listen 443 ssl; server_name chat.xutongbao.top;ssl_certificate /temp/ssl/chat.xutongbao.top/chat.xutongbao.top.crt; # nginx的ssl证书文件ssl_certificate_key /temp/ssl/chat.xutongbao.top/chat.xutongbao.top.key; # nginx的ssl证书验证密码#配置根目录location / {root /temp/yuying;index index.html index.htm;add_header Content-Security-Policy upgrade-insecure-requests;}location /api/ {proxy_set_header X-Real-IP $remote_addr;proxy_set_header REMOTE-HOST $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-NginX-Proxy true;proxy_pass http://yuying-api.xutongbao.top;}location /socket.io/ {proxy_set_header X-Real-IP $remote_addr;proxy_set_header REMOTE-HOST $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-NginX-Proxy true;proxy_pass http://127.0.0.1:84;# 关键配置 startproxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";# 关键配置 end}# 匹配sslCnd开头的请求,实际转发的请求去掉多余的sslCnd这三个字母location ^~/sslCnd/ {proxy_set_header X-Real-IP $remote_addr;proxy_set_header REMOTE-HOST $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-NginX-Proxy true;proxy_pass http://cdn.xutongbao.top/;} }
nginx配置错误会报错: