node.js - Using socket.io with net socket in nodejs -
is there way can use socket.io net socket in nodejs ? @ end have main service listen on port , waiting connection (net socket) , main while listen client's want establish connection using socket.io .
example scenario:
main service running listing on port x connection request client service .
client's open web browser connected main service using http server
in case of incoming data client service (server b) through net socket , data sent through socket.io connected client opening browser .
nodejs allow open 2 ports in same running process . following example shows :
main service listing on port 8124 incoming socket connection using net socket .
main service listen on port 8081 incoming http connection , client can receive data 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 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>
Comments
Post a Comment