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'
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.
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.
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.
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.
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.
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