简体   繁体   中英

Can WebSockets replace AJAX when it comes to Database requests?

This may seem like an extremely dumb question, but I am currently switching my Website from using the EventSource Polling constructor to the WebSocket standard which is implemented in Node.js.

Originally, all backend on my website was handled with PHP. With the introduction of Node.js, I am trying to switch as much as I can without going outside of the "standard". By standard, I meaning that typically I see WebSocket implementations that send small data, and receive small data back vs. performing database queries and then sending large amounts of data back to the client.

Can WebSockets replace AJAX when it comes to Database requests?


Let's consider a small hello world program in PHP/JavaScript (AJAX) vs Node.js/JavaScript (WebSockets)

PHP/JavaScript (AJAX)

// HelloWorld.php with Laravel in the Backend

Table::update([ 'column' => $_POST['message'] ]);
echo $_POST['message'];

Ajax.js with a custom ajax function

Global.request("HelloWorld.php").post({
     message: "Hello World"
}).then(message => alert(message));

Node.js/JavaScript (WebSockets)

// skip all the server setup
server.on('connection', function () {
     server.on('message', function (message) {
         sqlConnection.query("UPDATE `table` SET `column` = ?", [message], function () {
              server.send(message);
         });
     });
});

WebSocket.js:

let socket = new WebSocket('ws://example.com');

socket.onmessage = function (message) {
    alert(message)
}
socket.send("Hello World");

They both essentially do the same thing, in a slightly different way. Now, in this scale it would not make sense to use WebSockets. Though an example, imagine it scaled up to a point where Node.js is processing bigger queries and sending lots of data to the client. Is this acceptable?

Yes, theoretically, you could trigger a db query with websockets. Both HTTP and Websockets are built on TCP which do the job of transferring data of being a the bridge between network requests and responses.

The bigger issue is that Websockets were intended to lessen burden of opening/closing network ports, which you would have to do for ajax. This comes with several application-level benefits including real-time media streaming.

So what's the benefit of sticking with HTTP if you don't have a specific use case for web sockets? That HTTP is built has a robust ecosystem of tools - HTTP is largely plug & play. Think of stuff like security and standardization. Web sockets is a relatively new technology and hasn't developed this same ecosystem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM