因为现在的一些原因我想用 webscoket 进行并非使用 scoket.io
我个人想使用node尝试做一下
因为网上教程大多数是scoket.io
的绕了很多湾,
最后发现要使用webscoket弄得直接引入ws
模块
代码如下
const WebSocket = require('ws');
const ws = new WebSocket.Server({port:4577,path:'/wscoketd'});
port
为端口号
path
为前路径
让webscoket返回信息代码如下:
ws.on('connection',function(ws){ //初始化
console.log('ws已经连接')
ws.on('message',function(message){ // 接收到客户端发的消息
console.log(`收到客户端的数据: ${message}`);
if (message.indexOf('吗') > -1 ) {
var as = message.split('吗')[0]
ws.send(as) // 往客户端发的消息
}else{
ws.send('对不起网络有问题')
}
})
})
因为我就有一台服务器使用我要用nginx进行反向代理
问题发生了:
nginx低版本是不支持webscket反向代理的
而且需要配置:
#websocket 需要加下这个
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream wsbackend {
server 127.0.0.1:4577;
}
server
{
listen 80;
listen 443 ssl;
location /wscoketd
{
proxy_pass http://wsbackend;
#持久化连接相关配置
proxy_connect_timeout 30s;
proxy_read_timeout 86400s;
proxy_send_timeout 30s;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
add_header X-Cache $upstream_cache_status;
expires 12h;
}