我的React应用程序与nodejs socket.io应用程序聊天时,我目前遇到问题。
但是,我缩小了范围,并认为这是入口配置错误。端口转发socket.io nodejs pod并通过127.0.0.1:3020与react连接正常。
Socket.io部署文件
0
套接字IO服务配置
apiVersion: apps/v1
kind: Deployment
metadata:
name: websockettest-deployment
spec:
replicas: 1
selector:
matchLabels:
component: websockettest
template:
metadata:
labels:
component: websockettest
spec:
containers:
- name: websockettest
image: websockettest
imagePullPolicy: IfNotPresent
ports:
- containerPort: 3020
入口配置
apiVersion: v1
kind: Service
metadata:
name: websockettest-cluster-ip-service
spec:
type: ClusterIP
selector:
component: websockettest
ports:
- port: 3020
targetPort: 3020
Nodejs Socket.io
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: ingress-service
annotations:
kubernetes.io/ingress.class: nginx
nginx.org/websocket-services: websockettest-cluster-ip-service
spec:
rules:
- http:
paths:
- path: /websockettest/?(.*)
backend:
serviceName: websockettest-cluster-ip-service
servicePort: 3020
反应Socket.io客户端
const http = require('http');
const express = require('express');
var app = express();
var server = http.createServer(app);
var io = require('socket.io')(server);
io.set("transports", ["websocket"]);
io.on('connection', function (socket) {
console.log('connected socket!');
socket.on('greet', function (data) {
console.log(data);
socket.emit('respond', { hello: 'Hello' });
});
socket.on('disconnect', function () {
console.log('Socket disconnected');
});
});
const port = process.env.PORT || 3020;
server.listen(port, () => {
console.log(`Server is up on port ${port}`);
});
答案 0 :(得分:3)
Socket.io具有用于Websocket通信的特定路径。因此,需要将kubernetes入口配置为支持“ /socket.io”。此外,node.js中间件还需要具有用于套接字端点的自定义名称空间。
ingress-ws-service.yaml
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: ingress-ws-service
annotations:
nginx.ingress.kubernetes.io/use-regex: "true"
nginx.org/websocket-services: "websockettest-cluster-ip-service"
spec:
rules:
- http:
paths:
- path: /websockettest/.*
backend:
serviceName: websockettest-cluster-ip-service
servicePort: 3020
- path: /socket.io/.*
backend:
serviceName: websockettest-cluster-ip-service
servicePort: 3020
Nodejs Socket.io
const http = require('http');
const express = require('express');
var app = express();
var server = http.createServer(app);
var io = require('socket.io')(server);
const nsp = io.of("/websockettest");
nsp.on('connection', function (socket) {
console.log('connected socket!');
socket.on('greet', function (data) {
console.log(data);
nsp.emit('respond', { hello: 'Hello' });
});
socket.on('disconnect', function () {
console.log('Socket disconnected');
});
});
const port = process.env.PORT || 3020;
server.listen(port, () => {
console.log(`Server is up on port ${port}`);
});
反应客户
const socket = io('/websockettest', {
'reconnection': true,
transports: ['websocket']
});