Apansson
Apansson

Reputation: 104

RxJS.fromWebSocket with Socket.io

I'm trying to create a Subject using Rx.DOM.fromWebSocket with Socket.io. I'm really lost - where do I find the protocol for the Socket.io implementation?

var rxSocket = Rx.DOM.fromWebSocket(
        'ws://localhost:12345',
        'ws',
        function (e) {
            console.log('Opening');
        });

rxSocket.subscribe(function (next) {
    console.log('Received data: ' + next);
});

rxSocket.onNext('data');

This is what I've got right now. I'm trying to connect locally, to my server running Socket.io. When I just used the standard io.connect() everything runs smoothly, so my server is up and running Socket.io. I've tried to Google but don't know where to find the socket protocol implementation for Socket.io.

Upvotes: 2

Views: 4429

Answers (3)

MoshMage
MoshMage

Reputation: 506

Shamless self promotion, I know, but I made rxjs-socket.io for this propose exactlty. with it, all you really have to do is:

import {IO, ioEvent} from 'rxjs-socket.io'

const socket = new IO();
const onHelloWorld = new ioEvent({name: "hello-world", once: false, count: 0});

socket.listenToEvent(onHelloWorld);
socket.connect('http://localhost:1337');

onHelloWorld.event$.subscribe((state) => {
    console.log('new state', state);
});

Upvotes: 0

Rudi Starcevic
Rudi Starcevic

Reputation: 685

Another approach is to use RxJS Observable.fromEvent.

var socket = io('ws://localhost:8080');

var dataStream = Rx.Observable.fromEvent(socket, 'data');

dataStream.subscribe(function(payload) {
  console.log(payload);
});

In this example, allow socket.io to handle the connection.

RxJs handles the events and creates an Observable stream to subscribe to.

Upvotes: 7

generalhenry
generalhenry

Reputation: 17319

Socket.io doesn't serve websockets, it serves 'websockets', websockets if available but fallbacks if not, even if it makes a websocket connection it doesn't send the kind of messages rxSocket is going to expect. If you want to use Rx.DOM.fromWebSocket you should instead simple use the ws module.

So options:

  • RX.DOM.formWebSocket + ws (only support real websockets, but make things nice)
  • socket.io + hacks (full browser/ 'helpful' proxy support, but clunky)

Upvotes: 3

Related Questions