jeff jeff - 4 days ago 5
Node.js Question

What did I just implement with Node.js?

I'm following this tutorial, I was confused at the point where it says:

"...
Surprisingly the code is very simple:"

// Connect to the socket.io server
var socket = io.connect('http://localhost:8080');
// Wait for data from the server
socket.on('output', function (data) {
...


I'm not sure where to put this code. I tried to add it to browser JS, like this:

<html>
<head>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script> <!-- here -->
// Connect to the socket.io server
var socket = io.connect('http://localhost:8080');
// ...
</script>
</head>
<body>
<h1>SSH</h1>
<div class="terminal"></div>
</body>
</html>


And it worked! Is this correct? I thought it was meant to be a server-side code.

Anyways, now I get a terminal which i can interact with. But I'm not sure what it is doing. I was trying to implement an SSH client, but it looks like I obtained an on-browser terminal, over which I will manually connect to SSH?

Also I believe this would only work on the local machine. But what I want is a -remote- web server that can access to my machine using SSH (although it may not be very safe). Am I in the right direction? How can I implement a web server that acts as a client to the SSH server on my machine?

Thanks,

Answer

It has absolutely NOTHING to do with SSH in any way, shape or form. It's a websocket server/client, which allows you to send messages(not commands) between a browser and a server.

It's most commonly used for chat applications, although there are endless other uses.

However, with this mechanism in place, you could interpret certain messages on the server and make them execute the commands you wish to allow your users to use.

Quick example of how it would work (server side) :

socket.on('ls',(path,cb)=>{
    fs.readdir(path, (err, files) => {
        cb(files);
    });
});

and on the client :

socket.emit('ls','/home',(files)=>{
    console.log(files);
};

The client here emits a 'ls' event, with a path (user selected or something); and the server interprets this message, get the list of files for the given path, and returns it to the client. This mechanism could be used to implement a variety of commands. But keep in mind that this is NOT SSH.

Read more on Socket.io

Comments