Build your own TCP log server with node.js part 2

Eran Goldman-Malka · May 23, 2017

In this part we’ll build the front end in express and connect the socket.io

Express :

cd [your project dir]
mkdir logserverFE
cd logserverFE
sudo npm i -g generator-express
sudo npm install -g bower
yo express
#----#
? Would you like to create a new directory for your project? No
? Select a version to install: Basic
? Select a view engine to use: Jade
? Select a css preprocessor to use (Sass Requires Ruby): None
? Select a build tool to use: Grunt
#---#
grunt

And now you have simple server that runs on port 3000, you can point your browser to see it working

npm i socket.io --save
npm i jquery --save

grun

we’ll run the server and edit live, recently I like to use atom but any editor will work

edit views/index.jade :

block content
h1 Hello World!
#future
form#form
  input#chat_input(type='text')
  input(type='submit', value='Send')
script(src='https://code.jquery.com/jquery-1.10.2.js')
script(src='/socket.io/socket.io.js')
script(src='/js/socketio.js')

after ”var app = express(); ” in app.js add:

var socket_io = require('socket.io');
app.io = socket_io();

app.io.on('connection', function(client) {
 console.log('Client connected...');
 console.log("Client id : " + client.id);
 });

var routes = require('./routes/index');

add at the end of bin/www :


and now the server transmit emit messages to all connected browsers …

now we need to transmit incoming tcp messages :

add at the end of bin/www :

// tcp server net.createServer(function(socket){ socket.on(‘data’,function(data){ app.io.emit(‘messages’, String(data)); }); }).listen(3001);

And last one for this part :  
we add new file public/js/socketio.js :

var url = window.location.href; var socket = io.connect(url); socket.on(‘connect’, function(data) { socket.emit(‘join’, ‘Hello from client’); }); socket.on(‘messages’, function(data) { $(“#future”).empty().append(data); }); ```

Twitter, Facebook