First steps with WebSocket and Node.js (and Socket.io)
Demonstrates how to send notifications to a web page via WebSocket with Node.js at the source, on the server, or locally.
We will see that using WebSocket it is easy to create an HTML interface 5 for a local application. Other applications are possible, such as remote control of the robot.
we give out
The socket.io API contains two communication methods that work on the client or server side, emit and on. Other methods are used to start the connection.
- transferred
- Sending data. The parameter has such code as, for example, "notification," and the other side reacts to this command in a way that has the same code.
- Responds to the sending of data by the other party and calls the function provided as a parameter to process this data.
- connection
- Starts a client-requested connection to the server. It has a server name, by default it is not installed.
- list
- Creates a listener (listener) - a function that intercepts client interventions.
The interface script first creates a server object, then a socket.io object, then a listener. It sends an HTML page to the client.
The web page, after displaying on the client side, creates a socket object and establishes a connection:
var socket = io.connect();
socket.on('notification', function(x) { notification(x); });
The notification function is a handler that waits for a response from the server and processes the data that the server sends. In our example, the processing is to place the received data in a layer whose id is "storage."
The server intercepts the client request with the on:
listener.sockets.on('connection', function (socket) { start(socket);} );
He responds with the command:
socket.emit('notification', 'Server online via socket!');
All this happens when the page loads. Now let's see how to achieve real user-server interaction.
Interaction with the server
For real interaction, it is necessary that the page sends a request to the server at the request of the user and displays the data transmitted by the server in response.
To demonstrate this, add a button to the page. When the user clicks this button, the JavaScript callserver function is executed.
The HTML page then starts the exchange with the server-side script using the emit command.
socket.emit('called', 'Nothing');
The server intercepts the request and sends a new message in response to the "called" command. This message is a JSON data set that we presented here with the string ':
socket.emit('notification', 'Yes still here! Want some data?');
On the client side, always the same handler receives data and displays content.
socket.on('notification', function(x) { notification(x); });
In practice, the content will be a set of value keys, with the keys corresponding, for example, to text fields on an HTML page, and the value to the content to be displayed on it.
Here's the full source code for both files...
Server-side script, socket-mini.js
var uri="/socket-mini.html";
var fs = require('fs'),
http = require('http'),
socket = require("socket.io");
var page = fs.readFileSync(__dirname + uri);
function handler(request, response)
{
response.write(page);
response.end();
}
var app = http.createServer(function(r, s){ handler(r,s); });
app.listen(1000);
var listener = socket.listen(app, { log: false });
function start(socket)
{
socket.emit('notification', 'Server online via socket!');
socket.on('called', function(){
console.log("Request received.");
listener.sockets.emit('notification', 'Yes still here! Want some data?');
});
}
listener.sockets.on('connection', function (socket) { start(socket);} );
To start the server, enter the command line:
node socket-mini.js
The server responds to only two types of requests: "connection" and "called," the first is predefined, the second was created by our demonstration .
You can create any number of queries. If you want to avoid defining a function for each, you can put a key-value array in the data sent by "called," each key corresponds to a command and each value provides parameters for it.
Client side script, socket-mini.html
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title></title>
</head>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect();
function notification(content)
{
var x= document.getElementById("storage");
x.innerHTML = content;
console.log(content);
}
socket.on('notification', function(x) { notification(x); });
function callserver()
{
socket.emit('called', 'Nothing');
}
</script>
<body>
<h1>Notification from server by socket.io</h1>
<fieldset><legend>Messages received</legend>
<div id="storage"></div>
</fieldset>
<form name="form1" method="post" action="">
<input type="button" value="Call server" onClick="callserver()">
</form>
</body>
</html>
This page is sent by the server and displayed by the browser when you enter the browser URL:
localhost:1000
This demonstration is limited to one HTML page set as a parameter to the server and assigned to the variable uri (which is enough to create an application with an HTML interface). Based on previous tutorials, including "How to Create a Page Server with Node.js," you can make it more general and use different HTML pages with the same server script. Advanced Explorer provides full information about this in the "Scripts" section.
Only we are interested in the socket-mini.html and socket-mini.js files for this article.