rxjs/webSocket - 连接到 'ws://localhost:3000/' 的 WebSocket 失败:在接收到握手响应之前连接已关闭。

5

我已在后端初始化了WebSocket。
然后使用rxjs/webSocket进行连接,并在浏览器上收到以下错误:

connection to 'ws://localhost:3000/' failed: Connection closed before receiving a handshake response

与 server.js 相关的代码:

const { app, onServerInitialized } = require('./app');

const port = normalizePort(process.env.PORT);
console.log('Server is running on port ' + process.env.PORT);
app.set('port', port);

const server = http.createServer(app);
onServerInitialized(server);

与app.js相关的代码:

const app = express();

const onServerInitialized = server => {
    const io = socketio(server);

    io.on('connection', socket => {
        console.log('subscrie');
    });
};

module.exports = { app, onServerInitialized };

WebSocketService

import { webSocket, WebSocketSubject } from 'rxjs/webSocket';

export class WebSocketService {
    private ws$: WebSocketSubject<any> = webSocket('ws://localhost:3000');

    public getWSListener() {
        return this.ws$.asObservable().pipe();
    }

    public sendMessage(message: string) {
        this.ws$.next({ message });
    }
}

app.component.ts

constructor(
  private webSocketService: WebSocketService,
) {}

ngOnInit() {
  this.webSocketService.getWSListener().subscribe(() => {
    console.log('event')
  });
}
1个回答

8

您正在使用socket.io包,并且此包在/socket.io路径上设置了服务器。因此,请尝试使用此URI:ws://localhost:3000/socket.io/?EIO=3&transport=websocket

另外,请确保在onServerInitialized函数中,您不需要在底部添加此行

io.listen(+process.env.PORT);

编辑:

最好在Angular项目中使用ngx-socket-io包。


2
然后尝试使用此URI:ws://localhost:3000/socket.io/?EIO=3&transport=websocket,但恐怕您必须使用ngx-socket-io包。 - Damian Plewa
成功了!你能解释一下为什么我们需要这个参数吗? - Ron Rofe
EIO is Engine.IO version, in this case version is 3 - latest, transport parameter is forcing protocol, because socket.io can work on http and ws - Damian Plewa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接