- Socket.IO Cookbook
- Tyson Cadenhead
- 665字
- 2021-07-09 21:49:10
Using Socket.IO as a cross-browser WebSocket
The native WebSocket implementation in browsers is much less robust than what Socket.IO offers. Sending a WebSocket message from the client only requires the data as a single argument. This means that you have to format your WebSocket data in such a way that you can easily determine what it is for.
If you want to emulate the ease of sending a message without a topic, you can use the socket.send()
method to send messages as needed.
The benefits of using the Socket.IO syntax for this type of interaction over plain WebSockets are numerous. They include the built-in fallbacks for browsers that don't support WebSockets. The benefits also include a single unified syntax that is easier to read and maintain.
Getting ready
To get started with Socket.IO as a cross-browser WebSocket, you will need to have Node, Express, and Socket.IO installed. If you have not installed them yet, refer to the previous recipe: Creating an Express server with Socket.IO.
How to do it…
Follow these instructions to use Socket.IO as a cross-browser WebSocket:
- First, you'll need to set up your server-side
server.js
file as follows:var io = require('socket.io')(5000), sockets = []; io.on('connection', function (socket) { sockets.push(socket); socket.on('message', function (message) { for (var i = 0; i < sockets.length; i++) { sockets[i].send(message); } }); socket.on('disconnect', function () { console.log('The socket disconnected'); }); });
- Next, you'll have to create a client-side
index.html
file with the following code:<!doctype html> <html> <head></head> <body> <form id="my-form"> <textarea id="message" placeholder="Message"></textarea> <p> <button type="submit">Send</button> </p> </form> <div id="messages"></div> <script src="http://localhost:5000/socket.io/socket.io.js"></script> <script> var socket = io('http://localhost:5000'); socket.on('connect', function () { document .getElementById('my-form') .addEventListener('submit', function (e) { e.preventDefault(); socket.send(document.getElementById('message').value); }); socket.on('message', function (message) { var messageNode = document.createTextNode(message), messageElement = document.createElement('p'); messageElement.appendChild(messageNode); document.getElementById('messages').appendChild(messageElement); }); }); </script> </body> </html>
- In our example, we have a simple form that allows the user to post a message that will be sent to all the connected sockets.
- If you start your server with
node server
and open yourindex.html
file by navigating tohttp://5000/index.html
in your browser, you should see the form on the index page: - If you post a message to the form, it should send it to the server, and the server should broadcast it to all the available clients, as shown in the following screenshot:
How it works…
The socket.send(...)
method is a shortcut for socket.emit('message', ...)
. We will take a look at this topic in Chapter 3, Having Two-Way Conversations. This is the reason when the server listens for a message topic, it gets called when the client calls socket.send()
.
Our server stores an array of all the topics that connect to it. We will loop through all the connected sockets to send the message when it comes. We will also explore better ways to manage the connected sockets in the next chapter.
The client side aids the duty of sending the data from the form to the server. It also listens for new messages from the server to add to the list of available messages in our UI underneath the form.
There's more…
We will keep an array of all the connected sockets so that we will be able to easily send data to all of them as needed. However, keeping an array of all the connected sockets can be a little more tedious than just pushing the sockets to the array when they connect. For example, if a user leaves the page, the socket will disconnect, but it will still be included in the static array.
Fortunately, we will be able to tap into the socket disconnect event by calling socket.on('disconnect')
. Using this method, we can remove the socket from our array and avoid sending messages to an abandoned socket connection.
Here is an example of how the disconnect event can be used to manage dropped connections:
var io = require('socket.io')(5000), sockets = []; io.on('connection', function (socket) { sockets.push(socket); socket.on('disconnect', function () { for (var i = 0; i < sockets.length; i++) { if (sockets[i].id === socket.id) { sockets .splice(i, 1); } } console.log('The socket disconnected. There are ' + sockets.length + ' connected sockets');}); });
- Python概率統計
- 測試驅動開發:入門、實戰與進階
- C語言程序設計(第2 版)
- Python深度學習
- AngularJS Web Application Development Blueprints
- Python數據分析(第2版)
- Mastering ServiceNow(Second Edition)
- Hands-On Swift 5 Microservices Development
- Python算法從菜鳥到達人
- Procedural Content Generation for C++ Game Development
- Python爬蟲、數據分析與可視化:工具詳解與案例實戰
- Learning Material Design
- Beginning C++ Game Programming
- Machine Learning With Go
- Clean Code in C#