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')
});
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With