Using socket.io with net socket in nodejs

10,934

Nodejs allow to open 2 ports in the same running process . The following example shows :

  • Main service listing on port 8124 for any incoming socket connection using net socket .

  • Main service listen on port 8081 for any incoming http connection and client can receive any data from main service using socket.io

Expressjs version : 4.13.3
socket.io version : 1.3.7

Example :

Main service

var express = require('express');
var app = express();
var server = require("http").Server(app);
var io = require("socket.io")(server);
var net = require('net');


var netServer = net.createServer(function(c) {
  console.log('client connected');

  c.on('end', function() {
    console.log('client disconnected');
  });

  c.write('hello\r\n');
  c.pipe(c);
});

// main service listing to any service connection on port 8124
netServer.listen(8124);

app.get('/', function (req, res) {
  res.sendFile(__dirname+'/index.html');
});

app.use(express.static(__dirname+'/static'));

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});
server.listen(8081);

Client Service (Server B):

   var net = require('net');

var client = new net.Socket();
client.connect(8124, '127.0.0.1', function() {
    console.log('Connected');
    client.write('Hello, server! Love, Client.');
});

client.on('data', function(data) {
    console.log('Received: ' + data);
});

client.on('close', function() {
    console.log('Connection closed');
});

index.html

<script src="/js/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost:8081');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>
Share:
10,934
uno-2017
Author by

uno-2017

Updated on June 13, 2022

Comments

  • uno-2017
    uno-2017 almost 2 years



    Is there a way that i can use socket.io with net socket in nodejs ? so at the end i have main service that listen on port , waiting for connection (net socket) and main while listen to client's want establish connection using socket.io .

    Example scenario:

    • Main service running listing on port X for any connection request from client service .

    • client's open web browser connected to the main service using http server

    • in case of any incoming data from client service (server B) through net socket , the data will be sent through socket.io to connected client opening browser .



    Digram

  • Elialber Lopes
    Elialber Lopes over 5 years
    Great Job, but, what if server B was a telnet?
  • Qiulang
    Qiulang over 2 years
    Hi, what does c.pipe(c); use for ?