websocketsocket.iorxjsrxjs-dom

RxJs webSocket not able to connect to a websocket server implemented with socket.io


I have a simple websocket server built following this example

import { createServer, Server } from 'http';
import * as express from 'express';
import * as socketIo from 'socket.io';

export class MobileObjectServer {
    public static readonly PORT:number = 8081;
    private app: express.Application;
    private server: Server;
    private io: socketIo.Server;
    private port: string | number;

    constructor() {
        this.createApp();
        this.config();
        this.createServer();
        this.sockets();
        this.listen();
    }

    private createApp() {
        this.app = express();
    }

    private createServer() {
        this.server = createServer(this.app);
    }

    private config() {
        this.port = process.env.PORT || MobileObjectServer.PORT;
    }

    private sockets() {
        this.io = socketIo(this.server);
    }

    private listen() {
        this.server.listen(this.port, () => {
            console.log('Running server on port %s', this.port);
        });

        this.io.on('connect', (socket: any) => {
            console.log('Connected client on port %s.', this.port);
            socket.on('message', m => {
                console.log('[server](message): %s', JSON.stringify(m));
                this.io.emit('message', m);
            });

            socket.on('disconnect', () => {
                console.log('Client disconnected');
            });
        });
    }

    public getApp(): express.Application {
        return this.app;
    }
}

This code runs smoothly. I can launch the websocket server on my machine and I can connect if I use the socket.io-client library.

Now I would like to connect to such server from a client using the webSocket and WebSocketSubject facilities provided by RxJs but I am encountering some basic problems just trying to connect.

If I do

import { webSocket } from 'rxjs/observable/dom/webSocket';
webSocket('http://localhost:8081')

nothing happens, no connection is established.

If I use 'ws://localhost:8081' as connection string then I get an error like this

WebSocketSubject.js:142 WebSocket connection to 'ws://localhost:8081/' failed: Connection closed before receiving a handshake response

I am sure I am making a very basic mistake, but I have currently no clue on where.


Solution

  • It is more or less impossible to connect to a socket.io server with pure web sockets. Socket.io adds a lot on top of the Websocket standard that is not compatible with pure web sockets. if you want to skip using socket.io on the client side I would advice using some other library server side, one example would be ws