Socket.IO is a library that enables low-latency, bidirectional and event-based communication between a client and a server. It is built on top of the WebSocket protocol and provides additional guarantees like fallback to HTTP long-polling or automatic reconnection.
Socket.IO is a library that enables real-time, bidirectional and event-based communication between the browser and the server. It consists of: a Node. js server: Source | API. a Javascript client library for the browser (which can be also run from Node.
In order to do it, you need to create an index. js file and install socket.io and express. You can use the following command: touch index. js && npm install express socket.io && npm install --save-dev nodemon .
Edit: I feel it's better for anyone to consult the excellent chat example on the Socket.IO getting started page. The API has been quite simplified since I provided this answer. That being said, here is the original answer updated small-small for the newer API.
Just because I feel nice today:
<!doctype html>
<html>
<head>
<script src='/socket.io/socket.io.js'></script>
<script>
var socket = io();
socket.on('welcome', function(data) {
addMessage(data.message);
// Respond with a message including this clients' id sent from the server
socket.emit('i am client', {data: 'foo!', id: data.id});
});
socket.on('time', function(data) {
addMessage(data.time);
});
socket.on('error', console.error.bind(console));
socket.on('message', console.log.bind(console));
function addMessage(message) {
var text = document.createTextNode(message),
el = document.createElement('li'),
messages = document.getElementById('messages');
el.appendChild(text);
messages.appendChild(el);
}
</script>
</head>
<body>
<ul id='messages'></ul>
</body>
</html>
var http = require('http'),
fs = require('fs'),
// NEVER use a Sync function except at start-up!
index = fs.readFileSync(__dirname + '/index.html');
// Send index.html to all requests
var app = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
});
// Socket.io server listens to our app
var io = require('socket.io').listen(app);
// Send current time to all connected clients
function sendTime() {
io.emit('time', { time: new Date().toJSON() });
}
// Send current time every 10 secs
setInterval(sendTime, 10000);
// Emit welcome message on connection
io.on('connection', function(socket) {
// Use socket to communicate with this particular client only, sending it it's own id
socket.emit('welcome', { message: 'Welcome!', id: socket.id });
socket.on('i am client', console.log);
});
app.listen(3000);
Here is my submission!
if you put this code into a file called hello.js and run it using node hello.js it should print out the message hello, it has been sent through 2 sockets.
The code shows how to handle the variables for a hello message bounced from the client to the server via the section of code labelled //Mirror.
The variable names are declared locally rather than all at the top because they are only used in each of the sections between the comments. Each of these could be in a separate file and run as its own node.
// Server
var io1 = require('socket.io').listen(8321);
io1.on('connection', function(socket1) {
socket1.on('bar', function(msg1) {
console.log(msg1);
});
});
// Mirror
var ioIn = require('socket.io').listen(8123);
var ioOut = require('socket.io-client');
var socketOut = ioOut.connect('http://localhost:8321');
ioIn.on('connection', function(socketIn) {
socketIn.on('foo', function(msg) {
socketOut.emit('bar', msg);
});
});
// Client
var io2 = require('socket.io-client');
var socket2 = io2.connect('http://localhost:8123');
var msg2 = "hello";
socket2.emit('foo', msg2);
Maybe this may help you as well. I was having some trouble getting my head wrapped around how socket.io worked, so I tried to boil an example down as much as I could.
I adapted this example from the example posted here: http://socket.io/get-started/chat/
First, start in an empty directory, and create a very simple file called package.json Place the following in it.
{
"dependencies": {}
}
Next, on the command line, use npm to install the dependencies we need for this example
$ npm install --save express socket.io
This may take a few minutes depending on the speed of your network connection / CPU / etc. To check that everything went as planned, you can look at the package.json file again.
$ cat package.json
{
"dependencies": {
"express": "~4.9.8",
"socket.io": "~1.1.0"
}
}
Create a file called server.js This will obviously be our server run by node. Place the following code into it:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
//send the index.html file for all requests
res.sendFile(__dirname + '/index.html');
});
http.listen(3001, function(){
console.log('listening on *:3001');
});
//for testing, we're just going to send data to the client every second
setInterval( function() {
/*
our message we want to send to the client: in this case it's just a random
number that we generate on the server
*/
var msg = Math.random();
io.emit('message', msg);
console.log (msg);
}, 1000);
Create the last file called index.html and place the following code into it.
<html>
<head></head>
<body>
<div id="message"></div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('message', function(msg){
console.log(msg);
document.getElementById("message").innerHTML = msg;
});
</script>
</body>
</html>
You can now test this very simple example and see some output similar to the following:
$ node server.js
listening on *:3001
0.9575486415997148
0.7801907607354224
0.665313188219443
0.8101786421611905
0.890920243691653
If you open up a web browser, and point it to the hostname you're running the node process on, you should see the same numbers appear in your browser, along with any other connected browser looking at that same page.
i realize this post is several years old now, but sometimes certified newbies such as myself need a working example that is totally stripped down to the absolute most simplest form.
every simple socket.io example i could find involved http.createServer(). but what if you want to include a bit of socket.io magic in an existing webpage? here is the absolute easiest and smallest example i could come up with.
this just returns a string passed from the console UPPERCASED.
app.js
var http = require('http');
var app = http.createServer(function(req, res) {
console.log('createServer');
});
app.listen(3000);
var io = require('socket.io').listen(app);
io.on('connection', function(socket) {
io.emit('Server 2 Client Message', 'Welcome!' );
socket.on('Client 2 Server Message', function(message) {
console.log(message);
io.emit('Server 2 Client Message', message.toUpperCase() ); //upcase it
});
});
index.html:
<!doctype html>
<html>
<head>
<script type='text/javascript' src='http://localhost:3000/socket.io/socket.io.js'></script>
<script type='text/javascript'>
var socket = io.connect(':3000');
// optionally use io('http://localhost:3000');
// but make *SURE* it matches the jScript src
socket.on ('Server 2 Client Message',
function(messageFromServer) {
console.log ('server said: ' + messageFromServer);
});
</script>
</head>
<body>
<h5>Worlds smallest Socket.io example to uppercase strings</h5>
<p>
<a href='#' onClick="javascript:socket.emit('Client 2 Server Message', 'return UPPERCASED in the console');">return UPPERCASED in the console</a>
<br />
socket.emit('Client 2 Server Message', 'try cut/paste this command in your console!');
</p>
</body>
</html>
to run:
npm init; // accept defaults
npm install socket.io http --save ;
node app.js &
use something like this port test to ensure your port is open.
now browse to http://localhost/index.html and use your browser console to send messages back to the server.
at best guess, when using http.createServer, it changes the following two lines for you:
<script type='text/javascript' src='/socket.io/socket.io.js'></script>
var socket = io();
i hope this very simple example spares my fellow newbies some struggling. and please notice that i stayed away from using "reserved word" looking user-defined variable names for my socket definitions.
index.html
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
#messages { margin-bottom: 40px }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
window.scrollTo(0, document.body.scrollHeight);
});
});
</script>
</body>
</html>
index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(port, function(){
console.log('listening on *:' + port);
});
And run these commands for run the application.
npm init; // accept defaults
npm install socket.io http --save ;
node start
and open the URL:- http://127.0.0.1:3000/
Port may be different.
and you will see this OUTPUT
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With