Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have initialized WebSocket on my backend.
Then use rxjs/webSocket to connect and receive the following error on the browser:

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

server.js related code:

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 related code:

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')
  });
}
like image 416
Ron Rofe Avatar asked May 03 '20 08:05

Ron Rofe


1 Answers

You are using socket.io package, and this package has server setted up at /socket.io path. So try this uri: ws://localhost:3000/socket.io/?EIO=3&transport=websocket

Also make sure that in onServerInitialized function you don't need to add this line at the bottom

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

EDIT:

Better use ngx-socket-io package into Angular project

like image 94
Damian Plewa Avatar answered Oct 20 '22 01:10

Damian Plewa