在node环境下使用socket.io,需要在node服务端安装socket.io
客服端安装socket.io-client
服务端使用
const express = require("express")();
const http = require("http").createServer(express);
const io = require("socket.io")(http,{cors:true}); // 使用这个socket有跨域问题需要将cors设置为true
io.on("connect",(socket)=>{
//......
})
在服务端项目中使用的时候需要在项目根目录bin下使用(我将文件拆分开来使用)
socket.js
module.exports = {
getSocket:(server)=>{
const io = require("socket.io")(server,{cors:true})
io.on("connect",(socket)=>{
console.log("connect");
})
}
}
bin/www
//在顶部添加
const {getSocket} = require("../socket.js")
//然后需要在当前文件的(http/https).createServer()的后面加上
getSocket(httpSerer)
客户端使用
安装socket.io-client
npm i socket.io-client
使用
import io from 'socket.io-client'
const socket = io("ws://127.0.0.1:3000");
socket.on('connect',()=>{
alert(socket.connected)
})
或者使用cdn方式引入
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
使用
<script>
const socket = io("ws://127.0.0.1:3000");
socket.on('connect',()=>{
console.log("connect");
})
</script>
socket.io的事件类型(客户端)
connect | Fired upon connection (including a successful reconnection) |
disconnect | Fired upon disconnection |
connect_error | Fired upon a connection error |
connect_timeout | Fired upon a connection timeout |
reconnect_attempt | Fired upon an attempt to reconnect |
reconnect_error | Fired upon a reconnection attempt error |
reconnect_failed | Fired when the client couldn’t reconnect within reconnectionAttempts |
reconnecting | Alias for “reconnect_attempt” |
reconnect | Fired upon a successful reconnection |
ping | Fired when a ping is sent to the server |
pong | Fired when a pong is received from the server |
Nginx的socket.io配置
http { server { listen 3000; # 监听端口 server_name io.yourhost.com; # 你的域名 location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_pass http://nodes; # 你的转发链接 upstream nodes 跟这个有关系 # 相当于 http://app01:3000; # enable WebSockets proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } } upstream nodes { # enable sticky session based on IP ip_hash; server app01:3000; server app02:3000; server app03:3000; } }
详情请参考2022-12-12记(关于nginx配置socket.io的wss和ws代理(2022-12-12记)_StarCloud.的博客-CSDN博客)文章,关于wss和ws链接的nginx配置