4686

socket.io connect to unix socket

Question:

I want to connect to unix socket using socket.io-client, No success (mostly timeout, last sample - dns resolution error).

var clientio = require('socket.io-client'); // i tried all variants here //client=clientio.connect('port.io/',{'force new connection': true}); //client=clientio.connect('unix://port.io/',{'force new connection': true}); //client=clientio.connect('http//unix:port.io/',{'force new connection': true}); client.on('connect',connect);

Is there any way to connect socket.io client to unix socket ?

I checked server socket using nc -U port.io, it works fine.

Answer1:

Just found this while looking for answers to similar question.

AFAIK socket.io-client depends on engne.io-client, which depends on ws, which contains this:

var isUnixSocket = serverUrl.protocol === 'ws+unix:';

See here: <a href="https://github.com/websockets/ws/blob/4f99812b1095979afaad58865846b160334f3415/lib/WebSocket.js#L598" rel="nofollow">https://github.com/websockets/ws/blob/4f99812b1095979afaad58865846b160334f3415/lib/WebSocket.js#L598</a>.

So it looks like it might be possible to connect client through UNIX socket, as long as it is done in node.js (or something similar) - i don't think it is possible to do in a web browser.

<s>I did not try it, but maybe something like this will work:</s>

var client=clientio.connect('ws+unix:/port.io',{'force new connection': true});

<strong>Update:</strong> it looks like socket.io and engine.io really do not like UNIX domain sockets :(. To connect through UDS, direct use of ws module seems to be the only way, but then it will not know all the additional stuff that socket.io builds on top (like rooms and namespaces).

Answer2:

socket.io runs a specific protocol on top of a webSocket protocol which then runs on a plain TCP socket. If you are trying to connect to a plain Unix socket, then you cannot use socket.io.

You can use net.Socket described here: <a href="http://nodejs.org/api/net.html" rel="nofollow">http://nodejs.org/api/net.html</a> which according to that doc is "is an abstraction of a TCP or UNIX socket".

A socket.io connection has a very specific startup protocol that it uses and a very specific over the wire data format and a very specific message sequence and a heatbeat keep-alive strategy. Both ends must support all of that for a socket.io connection to work.

A plain socket is the root transport at the lowest level, but all this other stuff must exist on top of that plain socket for the two sides to be able to talk to one another using socket.io. See <a href="https://developer.mozilla.org/en-US/docs/WebSockets/Writing_WebSocket_servers" rel="nofollow">this article</a> if you want a concise overview of what is involved in writing a webSocket server. Socket.io is then another protocol on top of the webSocket transport.

<hr />

Still very confused here. I have no idea why you mention a standard Unix socket.

If you're trying to connect from one nodejs server to another nodejs server using socket.io and one of the servers is running the default socket.io server that you showed in your comments, then you should be able to do this from the other one to connect to the socket.io server:

var socket = require('socket.io-client')('http://port.io'); socket.on('connect', function(){}); socket.on('event', function(data){}); socket.on('disconnect', function(){});

This assumes that port.io is the domain of your socket.io server (something that can be resolved with DNS to point to an actual server). It's important that what you use must be an actual HTTP URL because all webSocket and socket.io connections are initiated with an HTTP request to an actual HTTP URL.

I don't follow what you're trying to do with Unix URL schemes.

Answer3:

Your question is vague, but since I came here looking for a similar answer, here is the code I came up with.

This code opens a unix domain socket, and broadcasts everything it receives to any connected socket.io clients (via WebSockets)

// Generated by CoffeeScript 1.9.2 var app, domain_server, fs, io, net, server; fs = require('fs'); net = require('net'); app = require('express')(); server = require('http').Server(app); io = require('socket.io')(server); /* Handle Unix Domain Socket * * Delete file if it already exists, * avoiding EADDRINUSE */ if (fs.existsSync('/tmp/domain_socket')) { fs.unlinkSync('/tmp/domain_socket'); } domain_server = net.createServer(function(socket) { socket.on('data', function(data) { /* broadcast messages from unix socket to websockets */ io.sockets.emit('domain-message', data.toString()); }); }); domain_server.listen('/tmp/domain_socket', function() { console.log('domain_server bound'); }); /* * Handle Web Serving/WebSockets */ server.listen(8080); app.get('/', function(req, res) { res.sendFile(__dirname + '/index.html'); }); io.on('connection', function(socket) { socket.emit('message', { hello: 'connected' }); });

Answer4:

sure we can do it.

client side (in node 8.11, not in browser):

var pipe_name = '/tmp/your-pipe-name'; var channel_name = '/your-namespace'; var server_url = "ws+unix://" + pipe_name + channel_name; var path = require('path'); var url = require('url'); var WebSocket = require('ws'); var mock = require('mock-require'); class WebSockeMock extends WebSocket { constructor (address, protocols, options) { var uri = url.parse(server_url); var param = url.parse(address).search; address = "ws+unix:///" + uri.host + path.dirname(uri.pathname) + ":/socket.io/" + param; console.log("real ws", address) super(address, protocols, options); } } console.log("connecting to " + server_url); if (/unix:\/+/.test(server_url)) { server_url = server_url.replace(/^[^:]+[:\/\\]+/, 'ws://'); console.log("fake ws", server_url); mock('ws', WebSockeMock); process.env.DEBUG = '*'; } var socket = require('socket.io-client')(server_url, { transports: ['websocket'] }); socket.on('connect', function() { return console.log("pipe connected"); });

server side:

var pipe_name = '/tmp/your-pipe-name'; var channel_name = '/your-namespace'; var fs = require('fs'); var path = require('path'); if (fs.existsSync(pipe_name)) { fs.unlinkSync(pipe_name); } console.log("pipe server at " + pipe_name); var io = require('socket.io')(require('http').createServer().listen(pipe_name)); var channel = io.of("/" + (path.basename(pipe_name)) + channel_name) .on('connection', function(socket) { console.log("unix pipe connected"); });

Recommend

  • Is Socket.IO a must in developing client apps for NodeJS servers?
  • Spring WebSockets XML configuration not providing brokerMessagingTemplate
  • What is “named let” and how do I use it to implement a map function?
  • Converting JsonNode to java array
  • Socket.io takes a long time before triggering the disconnect event
  • PDO connection to MySQL database refused
  • Cannot log in using SQL authentication ONLY from a remote server
  • Possible Autoit-like JavaScript macros?
  • Java: sl4j how to log for all classes?
  • Why has Haskell troubles resolving “overloaded” operators?
  • Help designing a order manager class
  • Javascript variables for Get http
  • miss prototype functions when “new” a instance
  • How to send an std::vector of unsigned char over an UDP socket using boost asio?
  • How to read data from socket connection - android
  • How can I set the buffer size for the underneath Socket UDP?
  • Cannot send user message with Spring Websocket
  • Installing SSL on AWS EC2 Bitnami Mean Stack
  • TSQL Rolling Average of Time Groupings
  • How can I let users share their location in Bot Framework webchat channel?
  • Error in making a socket connection
  • Synchronize windows folders
  • Easiest way to get current unix timestamp via XSL
  • HttpURLConnection Closing IO Streams
  • How to 'create temp table as select' in Slick?
  • Create Instant using a negative year
  • Parsing a CSV string while ignoring commas inside the individual columns
  • How to attach a node.js readable stream to a Sendgrid email?
  • PostgreSQL Query without WHERE only ORDER BY and LIMIT doesn't use index
  • Get object from AWS S3 as a stream
  • Cross-Platform Protobuf Serialization
  • Validaiting emails with Net.Mail MailAddress
  • JSON with duplicate key names losing information when parsed
  • Updated Ionic CLI but shows previous version (Windows)
  • Do I've to free mysql result after storing it?
  • How to get icons for entities from eclipse?
  • Proper way to use connect-multiparty with express.js?
  • Load html files in TinyMce
  • JaxB to read class hierarchy
  • How to Embed XSL into XML