gpt4 book ai didi

node.js - rxjs/webSocket - 到 'ws://localhost:3000/' 的 WebSocket 连接失败 : Connection closed before receiving a handshake response

转载 作者:行者123 更新时间:2023-12-03 12:12:14 25 4
gpt4 key购买 nike

我已经在我的后端初始化了 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 };

网络套接字服务

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')
});
}

最佳答案

您正在使用 socket.io包,这个包的服务器设置在 /socket.io小路。所以试试这个uri:ws://localhost:3000/socket.io/?EIO=3&transport=websocket
还要确保在 onServerInitialized功能你不需要在底部添加这一行

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

编辑:

更好用 ngx-socket-io 打包成Angular项目

关于node.js - rxjs/webSocket - 到 'ws://localhost:3000/' 的 WebSocket 连接失败 : Connection closed before receiving a handshake response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61571898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com