Socket.IO 在子域虚拟主机和代理上
Socket.IO on Subdomain vhost and proxy
我正在尝试将 socket.example.com:4000
代理到 websocket 服务器 mydomain.com:3000
但客户端也可以通过 *.example.com:4000
连接到服务器,就像 vhost
没有效果和代理配置是全局设置的。我不希望其他子域被代理。
我用vhost and http-proxy-middleware
const options = {
target: 'http://example.com:3000',
changeOrigin: true,
ws: true
};
const wsProxy = createProxyMiddleware(options);
app.use(vhost('socket.example.com', wsProxy));
我不需要虚拟主机,也不需要 http-proxy-middleware。我用了 http-proxy 和一些香草 javascript。
import httpProxy from 'http-proxy';
const proxy = httpProxy.createProxyServer({
target: {
host: 'example.com',
port: 4001
}
});
server.on('upgrade', (req, socket, head) => {
const domain = req.headers.host;
const host = domain.split(':')[0];
if (host === 'socket.example.com') {
proxy.ws(req, socket, head);
} else {
socket.destroy();
}
});
##更新##
运行 在没有代理或专用 websocket 服务器的同一台服务器上。
import { Server } from "socket.io";
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
allowRequest: (req, fn) => {
const domain = req.headers.host;
const host = domain.split(':')[0];
fn(null, host === `socket.example.com`);
}
});
io.on('connection', (socket) => {
console.log('a user connected');
});
我正在尝试将 socket.example.com:4000
代理到 websocket 服务器 mydomain.com:3000
但客户端也可以通过 *.example.com:4000
连接到服务器,就像 vhost
没有效果和代理配置是全局设置的。我不希望其他子域被代理。
我用vhost and http-proxy-middleware
const options = {
target: 'http://example.com:3000',
changeOrigin: true,
ws: true
};
const wsProxy = createProxyMiddleware(options);
app.use(vhost('socket.example.com', wsProxy));
我不需要虚拟主机,也不需要 http-proxy-middleware。我用了 http-proxy 和一些香草 javascript。
import httpProxy from 'http-proxy';
const proxy = httpProxy.createProxyServer({
target: {
host: 'example.com',
port: 4001
}
});
server.on('upgrade', (req, socket, head) => {
const domain = req.headers.host;
const host = domain.split(':')[0];
if (host === 'socket.example.com') {
proxy.ws(req, socket, head);
} else {
socket.destroy();
}
});
##更新## 运行 在没有代理或专用 websocket 服务器的同一台服务器上。
import { Server } from "socket.io";
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
allowRequest: (req, fn) => {
const domain = req.headers.host;
const host = domain.split(':')[0];
fn(null, host === `socket.example.com`);
}
});
io.on('connection', (socket) => {
console.log('a user connected');
});