


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: . 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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Introduction to Python functions: Introduction and examples of exec function Introduction: In Python, exec is a built-in function that is used to execute Python code stored in a string or file. The exec function provides a way to dynamically execute code, allowing the program to generate, modify, and execute code as needed during runtime. This article will introduce how to use the exec function and give some practical code examples. How to use the exec function: The basic syntax of the exec function is as follows: exec

The DECODE function in Oracle is a conditional expression that is often used to return different results based on different conditions in query statements. This article will introduce the syntax, usage and sample code of the DECODE function in detail. 1. DECODE function syntax DECODE(expr,search1,result1[,search2,result2,...,default]) expr: the expression or field to be compared. search1,

Indentation specifications and examples of Go language Go language is a programming language developed by Google. It is known for its concise and clear syntax, in which indentation specifications play a crucial role in the readability and beauty of the code. effect. This article will introduce the indentation specifications of the Go language and explain in detail through specific code examples. Indentation specifications In the Go language, tabs are used for indentation instead of spaces. Each level of indentation is one tab, usually set to a width of 4 spaces. Such specifications unify the coding style and enable teams to work together to compile

Introduction to Python functions: usage and examples of the abs function 1. Introduction to the usage of the abs function In Python, the abs function is a built-in function used to calculate the absolute value of a given value. It can accept a numeric argument and return the absolute value of that number. The basic syntax of the abs function is as follows: abs(x) where x is the numerical parameter to calculate the absolute value, which can be an integer or a floating point number. 2. Examples of abs function Below we will show the usage of abs function through some specific examples: Example 1: Calculation

Introduction to Python functions: Usage and examples of the isinstance function Python is a powerful programming language that provides many built-in functions to make programming more convenient and efficient. One of the very useful built-in functions is the isinstance() function. This article will introduce the usage and examples of the isinstance function and provide specific code examples. The isinstance() function is used to determine whether an object is an instance of a specified class or type. The syntax of this function is as follows

Introduction to Python functions: functions and examples of the eval function In Python programming, the eval function is a very useful function. The eval function can execute a string as program code, and its function is very powerful. In this article, we will introduce the detailed functions of the eval function, as well as some usage examples. 1. Function of eval function The function of eval function is very simple. It can execute a string as Python code. This means that we can convert a string

Introduction to Python functions: functions and examples of sorted functions Python is a very powerful programming language with a wealth of built-in functions and modules. In this series of articles, we will introduce the commonly used functions of Python one by one and provide corresponding examples to help readers better understand and apply these functions. This article will introduce the functions and examples of the sorted function in detail. The sorted function is used to sort an iterable object and return a new sorted list. Can be used for numbers and words

Application and example analysis of PHP dot operator In PHP, the dot operator (".") is an operator used to connect two strings. It is very commonly used and very flexible when concatenating strings. By using the dot operator, we can easily concatenate multiple strings to form a new string. The following will introduce the use of PHP dot operators through example analysis. 1. Basic usage First, let’s look at a basic usage example. Suppose there are two variables $str1 and $str2, which store two words respectively.
