Home > Article > Web Front-end > Introduction to HTML5 WebSocket 3 - Communication model socket.io_javascript skills
Why was socket.io born? Please see the text description below.
Why do you need socket.io?
Node.js provides an efficient server-side operating environment, but due to the different support for HTML5 on the browser side, in order to be compatible with all browsers, provide an excellent real-time user experience, and provide clients and services for programmers To provide a consistent programming experience, socket.io was born.
The design goal of socket.io is to support any browser and any mobile device. Currently supports mainstream PC browsers (IE, Safari, Chrome, Firefox, Opera, etc.) and Mobile browsers (iphone Safari/ipad Safari/android WebKit/WebOS WebKit, etc.).
Socket.io is based on node.js and simplifies the WebSocket API, unifying various communication APIs. It supports: WebSocket, Flash Socket, AJAX long-polling, AJAX multipart streaming, Forever IFrame, JSONP polling.
Socket.io solves real-time communication problems and unifies the programming methods of server and client. After starting the socket, it is like establishing a pipeline between the client and the server, and the two sides can communicate with each other.
Install
Execute in the command line: npm install socket.io to install.
Server-side programming model
Server-side programming is still the same as a normal server, starting the server, providing services, and processing events.
For example, the following server.js:
var http = require('http') , url = require('url') , fs = require('fs') , server; server = http.createServer(function(req, res){ // your normal server code var path = url.parse(req.url).pathname; switch (path){ case '/': res.writeHead(200, {'Content-Type': 'text/html'}); res.write('<h1>Hello! Try the <a href="/index.html">Socket.io Test</a></h1>'); res.end(); break; case '/index.html': fs.readFile(__dirname + path, function(err, data){ if (err) return send404(res); res.writeHead(200, {'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'}) res.write(data, 'utf8'); res.end(); }); break; default: send404(res); } }), send404 = function(res){ res.writeHead(404); res.write('404'); res.end(); }; server.listen(8080); var io = require('socket.io').listen(server); io.sockets.on('connection', function(socket){ console.log("Connection " + socket.id + " accepted."); socket.on('message', function(message){ console.log("Received message: " + message + " - from client " + socket.id); }); socket.on('disconnect', function(){ console.log("Connection " + socket.id + " terminated."); }); });
Client Programming Model
Client programming is also handled in a similar way, connecting to the server and exchanging information.
For example, the following index.html page:
<!doctype html> <html> <head> <title>Socket.io Test</title> <script src="/json.js"></script> <!-- for ie --> <script src="/socket.io/socket.io.js"></script> </head> <body> <script> var socket; var firstconnect = true; function connect() { if(firstconnect) { socket = io.connect(null); socket.on('message', function(data){ message(data); }); socket.on('connect', function(){ status_update("Connected to Server"); }); socket.on('disconnect', function(){ status_update("Disconnected from Server"); }); socket.on('reconnect', function(){ status_update("Reconnected to Server"); }); socket.on('reconnecting', function( nextRetry ){ status_update("Reconnecting in " + nextRetry + " seconds"); }); socket.on('reconnect_failed', function(){ message("Reconnect Failed"); }); firstconnect = false; } else { socket.socket.reconnect(); } } function disconnect() { socket.disconnect(); } function message(data) { document.getElementById('message').innerHTML = "Server says: " + data; } function status_update(txt){ document.getElementById('status').innerHTML = txt; } function esc(msg){ return msg.replace(/</g, '<').replace(/>/g, '>'); } function send() { socket.send("Hello Server!"); }; </script> <h1>Socket.io Test</h1> <div><p id="status">Waiting for input</p></div> <div><p id="message"></p></div> <button id="connect" onClick='connect()'/>Connect</button> <button id="disconnect" onClick='disconnect()'>Disconnect</button> <button id="send" onClick='send()'/>Send Message</button> </body> </html>
Notes
1. To start the server, leave it to node. Open the command line window, navigate to the folder where server.js is located, and enter node server.js to start the server.
In the index.html above, pay attention to this line: 73b0576f9b2d9a4f6808f937210380782cacc6d41bbb37262a98f745aa00fbf0. If you don’t want to use the local socket.io script, you can
To directly use the following public script:
<script src="http://cdn.socket.io/stable/socket.io.js"></script>
Also note this line: socket = io.connect(null).
The null here represents connecting to the local service, which can be replaced with "localhost" and the effect will be the same.
2. You can use socket.io to start the http service directly.
For example:
var io = require('socket.io').listen(80); io.sockets.on('connection', function (socket) { io.sockets.emit('this', { will: 'be received by everyone'}); });
3. Socket.io can send messages directly through the send method and receive messages using the message event, for example:
//server.js var io = require('socket.io').listen(80); io.sockets.on('connection', function (socket) { socket.on('message', function () { }); }); //index.html <script> var socket = io.connect('http://localhost/'); socket.on('connect', function () { socket.send('hi'); socket.on('message', function (msg) { // my msg }); }); </script>
4. Sending and processing data
Both ends can send events to each other, send data to each other, and communicate with each other. The code to send the event is: socket.emit(action, data, function), where action is the name of the event, data is the data, and function is the callback function; the code to process the event is: socket.on(action, function), if emit sends When there is data, the parameters in the function contain this data. In addition to sending and processing built-in events, socket.io such as connect, disconnect, message. Also allows sending and handling of custom events, such as:
//Server:
io.sockets.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); }); });
//Client:
<script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('http://localhost'); socket.on('news', function (data) { console.log(data); socket.emit('my other event', { my: 'data' }); }); </script>
5. As can be seen from the above, both send and emit can be used when sending data. It's just that emit strengthens the processing of custom events.
6. You can use the get/set method of socket on the server side to store relevant data on the client side, for example:
//Server
var io = require('socket.io').listen(80); io.sockets.on('connection', function (socket) { socket.on('set nickname', function (name) { socket.set('nickname', name, function () { socket.emit('ready'); }); }); socket.on('msg', function () { socket.get('nickname', function (err, name) { console.log('Chat message by ', name); }); }); });
//Client
<script> var socket = io.connect('http://localhost'); socket.on('connect', function () { socket.emit('set nickname', confirm('What is your nickname?')); socket.on('ready', function () { console.log('Connected !'); socket.emit('msg', confirm('What is your message?')); }); }); </script>
7. You can broadcast messages, such as sending messages to everyone in the chat room except the current socket connection.
var io = require('socket.io').listen(80); io.sockets.on('connection', function (socket) { socket.broadcast.emit('user connected'); });
8. Multiple independent channels can be established in the same link instead of establishing multiple links. This official name is "multiple namespaces", such as the official example:
var io = require('socket.io').listen(80); //Server var chat = io .of('/chat') .on('connection', function (socket) { socket.emit('a message', { that: 'only' , '/chat': 'will get' }); chat.emit('a message', { everyone: 'in' , '/chat': 'will get' }); }); var news = io .of('/news') .on('connection', function (socket) { socket.emit('item', { news: 'item' }); }); //Client <script> var chat = io.connect('http://localhost/chat') , news = io.connect('http://localhost/news'); chat.on('connect', function () { chat.emit('hi!'); }); news.on('news', function () { news.emit('woot'); }); </script>
socket.io configuration
The configuration of socket.io is very simple. If you have configured express, you will find that they use almost the same method. Let’s look at a small example first:
var io = require('socket.io').listen(80); io.configure('production', function(){ io.enable('browser client etag'); io.set('log level', 1); io.set('transports', [ 'websocket' , 'flashsocket' , 'htmlfile' , 'xhr-polling' , 'jsonp-polling' ]); }); io.configure('development', function(){ io.set('transports', ['websocket']); });
As you can see, socket.io uses configure, set, enable, and disable for configuration.
1. Use the configure method to configure the behavior in different operating environments; that is, enable different configuration options in different environments. The first parameter of configure is the running environment, and the second parameter is the function for configuration. The running environment is typically production or development. Of course, any string can be used here. If the first parameter of configure is omitted, it means that the subsequent configuration is public and valid no matter what environment it is.
2. After configuring various operating environments, how do you set which environment it is currently running in? This is achieved by modifying the value of the environment variable NODE_ENV on the command line.
3. In the configure configuration function, we can use set, enable, and disable to set related options.
4. Reference for specific configurable items: https://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO
Practical reference
Socket.io introduction: http://davidchambersdesign.com/getting-started-with-socket.io/
socket.io installation and usage instructions: http://socket.io/
socket.io Wiki: https://github.com/LearnBoost/Socket.IO/wiki