What is an example of the simplest possible example of socket.io?

So, I’ve been trying to understand Socket.io lately, but I’m not a super-serious programmer, and almost every example that I can find on the Internet (believe me, I looked for hours and hours) has additional materials that complicate the situation. Many examples contain a lot of things that confuse me, or connect to some strange database, or use coffeescript or tons of JS libraries that clutter things up.

I would like to see a basic, valid example, when the server simply sends a message to the client every 10 seconds, saying what time it is, and the client writes this data to the page or gives a warning, something is very simple. Then I can understand what is happening there, add the things I need, like db connections, etc. And yes, I checked the examples on socket.io and they don’t work for me, and I don’t understand what they are doing.

+85
Mar 28 2018-12-12T00:
source share
4 answers

Edit: I feel that it is best for everyone to consult with a great chat example at the beginning of the Socket.IO page. The API has been rather simplified since I gave this answer. That being said, here is the original answer, updated small-small for the new API.

Just because today I feel good:

index.html

<!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> 

app.js

 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 own id socket.emit('welcome', { message: 'Welcome!', id: socket.id }); socket.on('i am client', console.log); }); app.listen(3000); 
+129
Mar 28 2018-12-12T00:
source share

Here is my expression!

if you put this code in a hello.js file and run it using node hello.js, it should print a hello message, it was sent through 2 sockets.

The code shows how to process variables for a greeting message bouncing from a client to a server through a section of code with the inscription // Mirror.

Variable names are declared locally, and not all at the top, because they are used only in each of the sections between comments. Each of them can 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); 
+18
Feb 13 '15 at 7:51
source share

Perhaps this will help you too. I was having trouble getting my head wrapped around how socket.io works, so I tried to weld the example as much as possible.

I adapted this example from the example given here: http://socket.io/get-started/chat/

First, run in an empty directory and create a very simple file called package.json . Put the following into it.

 { "dependencies": {} } 

Next, on the command line, use npm to install the dependencies that we need for this example.

 $ npm install --save express socket.io 

This may take several minutes depending on the speed of your network connection / CPU / etc. To verify that everything went as planned, you can view 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 running node. Paste 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 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 put the following code in 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> 

Now you can test this very simple example and see some results similar to the following:

 $ node server.js listening on *:3001 0.9575486415997148 0.7801907607354224 0.665313188219443 0.8101786421611905 0.890920243691653 

If you open a web browser and point to the host name on which the node process is running, you should see that the same numbers are displayed in your browser along with any other connected browser that looks at the same page.

+14
Oct 21 '14 at 19:37
source share

I understand that this post has been around for several years, but sometimes certified beginners, such as myself, need a working example, completely divided into the simplest form.

every simple socket.io example i could find involved http.createServer (). but what if you want to incorporate a bit of socket.io magic into an existing web page? here is the simplest and smallest example i could come up with.

it just returns the string passed from the UPPERCASED console.

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> 

for start:

 npm init; // accept defaults npm install socket.io http --save ; node app.js & 

use something like this port test to make sure your port is open.

now go to http: //localhost/index.html and use the browser console to send messages to the server.

at best, suppose that when using http.createServer it changes the following two lines:

 <script type='text/javascript' src='/socket.io/socket.io.js'></script> var socket = io(); 

I hope this very simple example saves my fellow novices from some problems. and please note that I have stayed away from using a "reserved word" looking for custom variable names for my socket definitions.

+7
Jan 10 '16 at 18:36
source share



All Articles