1、首先配置nginx
加上下面一段
location / wss {
proxy_pass http://127.0.0.1:8181;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
}
server {
listen 443 ssl;
server_name www.test.cn;
ssl_certificate /usr/local/nginx/cert/www.pem;
ssl_certificate_key /usr/local/nginx/cert/www.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $http_addr;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#以上三行,目的是将代理服务器收到的用户的信息传到真实服务器上
root /root/www.test.cn/static;
index index.html index.htm;
}
location / wss {
proxy_pass http://127.0.0.1:8181;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
}
}
客户端连接:wss://www.test.cn/wss:8181
配置完后记得重启nginx
2、安装模块
npm install nodejs-websocket --save
3、搭建websocket服务端,这里建一个websocket.js文件
// 搭建websocket服务器
const ws = require('nodejs-websocket')
const wsServer = ws.createServer((conn) => {
// 接收到客户端返回的数据
conn.on('text', function (data) {
console.log('websocket接收到信息:', data)
conn.sendText(data)
})
//客户端关闭连接
conn.on('close', function (e) {
console.log('websocket连接关闭:', e)
})
// 服务端连接异常的回调方法
conn.on('error', function (err) {
console.log('websocket连接报错:', err)
})
})
const port = 8181
wsServer.listen(port, function () {
console.log('websocket连接成功')
})
4、客户端
//建立连接
var ws = new WebSocket('wss://www.test.cn/wss:8181')
ws.onopen = function (evt) {
console.log('WebSocket连接成功')
let sendobj = {
id: '0001',
name: '发送的值',
}
ws.send(JSON.stringify(sendobj))
}
ws.onmessage = function (e) {
console.log('接收到信息:')
console.log(e.data)
}
ws.onclose = function (evt) {
console.log('WebSocket关闭')
}
ws.onerror = function (err) {
console.log('WebSocket出错')
console.log(err)
}