Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open a Websocket connection from Meteor.js

How can we open a Websockets connection from Meteor?

Can we do something like:

ws = new WebSocket('ws://localhost/path');
ws.on('open', function() {
    ws.send('something');
});
ws.on('message', function(message) {
    console.log('received: %s', message);
});

Error: ReferenceError: WebSocket is not defined


Using socket.io npm package

var io = Meteor.require('socket.io')
var socket = io.connect('http://localhost');

Error: TypeError: Object # has no method 'connect'


Using ws npm package

var WebSocket = Meteor.require('ws');
var ws = new WebSocket('ws://localhost');

Error: Error: Cannot find module '../build/default/bufferutil'

like image 759
Nyxynyx Avatar asked Feb 07 '14 09:02

Nyxynyx


People also ask

How do I open a WebSocket connection?

To open a websocket connection, we need to create new WebSocket using the special protocol ws in the url: let socket = new WebSocket("ws://javascript.info"); There's also encrypted wss:// protocol. It's like HTTPS for websockets.

Does meteor use WebSockets?

These Meteor APIs use XHR (XMLHttpRequest) by SockJS. SockJS is WebSocket emulation utility. So when something changes on the server, SockJS ensures that an XHR is sent, and the changed data is in the JSON response. Yes, Meteor is fully dependent on Node.

How do I connect to a WebSocket endpoint?

In order to communicate using the WebSocket protocol, you need to create a WebSocket object; this will automatically attempt to open the connection to the server. The URL to which to connect; this should be the URL to which the WebSocket server will respond.

How do I check my WebSocket connection?

Identify that the application is using WebSockets. Inspect the client-side source code for the ws:// or wss:// URI scheme. Use Google Chrome's Developer Tools to view the Network WebSocket communication. Use ZAP's WebSocket tab.


1 Answers

I created a new Meteor package joncursi:socket-io-client to solve this problem. Please see https://atmospherejs.com/joncursi/socket-io-client for more detail and example usage. Since I've bundled the NPM binaries into a package for you, you don't have to worry about installing NPM packages, declaring NPM.require() dependencies, etc. And best of all, you can deploy to .meteor.com without a hitch.

like image 65
Jon Cursi Avatar answered Sep 24 '22 22:09

Jon Cursi