<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                ## 什么是 Socket.IO Socket.IO 是一個庫,可以在客戶端和服務器之間實現**低延遲**,**雙向**和**基于事件的**通信。 ![](https://img.kancloud.cn/c9/49/c9497048429c80c59ba368cf90b549f3_840x131.png) ## 版本差異 Socket.IO自誕生以來經歷了多個版本的迭代,主要版本有1.x、2.x和3.x。每個版本都帶來了新特性和性能改進。 * **1.x版本**:這是Socket.IO的初始版本,奠定了基礎架構。提供了基本的實時通信功能。 * **2.x版本**:引入了許多新特性,比如更好的錯誤處理機制、改進的協議、更加穩定的連接管理等。 * **3.x版本**:帶來了更高的性能和更低的延遲。它還增強了對TypeScript的支持,并優化了與其他框架的集成。 * **4.x版本**:基于WebSocket的通信協議已更新,以支持HTTP/2。客戶端和服務器之間的通信協議有所簡化。服務器和客戶端都已更新以使用更現代的JavaScript。服務器API有重大更改,以提高靈活性和簡化配置。移除了對Node.js的舊版本支持。 ## 語言實現 ### 服務器實現 |語言 | 網站 | |----------|---------------| | JavaScript (Node.js) | - [Installation steps](../02-Server/server-installation.md)<br/>- [API](../../server-api.md)<br/>- [Source code](https://github.com/socketio/socket.io) | | JavaScript (Deno) | https://github.com/socketio/socket.io-deno | | Java | https://github.com/mrniko/netty-socketio | | Java | https://github.com/trinopoty/socket.io-server-java | | Python | https://github.com/miguelgrinberg/python-socketio | | Golang | https://github.com/googollee/go-socket.io | | Rust | https://github.com/Totodore/socketioxide | PHP ? ? ? ? ? ? ? ? ?| https://github.com/walkor/phpsocket.io | ### 客戶端實現 | 語言| 網站 | |------------------|-----------------| | JavaScript (browser, Node.js or React Native) | - [Installation steps](../03-Client/client-installation.md)<br/>- [API](../../client-api.md)<br/>- [Source code](https://github.com/socketio/socket.io-client) | | JavaScript (for WeChat Mini-Programs) | https://github.com/weapp-socketio/weapp.socket.io | | Java | https://github.com/socketio/socket.io-client-java | | C++ | https://github.com/socketio/socket.io-client-cpp | | Swift | https://github.com/socketio/socket.io-client-swift | | Dart | https://github.com/rikulo/socket.io-client-dart | | Python | https://github.com/miguelgrinberg/python-socketio | | .Net | https://github.com/doghappy/socket.io-client-csharp | | Rust | https://github.com/1c3t3a/rust-socketio | | Kotlin | https://github.com/icerockdev/moko-socket-io | | PHP | https://github.com/ElephantIO/elephant.io | ## Socket.IO 不是什么 > Socket.IO 不是 WebSocket 實現。 盡管 Socket.IO 確實在可能的情況下使用 WebSocket 進行傳輸,但它會向每個數據包添加額外的元數據。這就是為什么 WebSocket 客戶端將無法成功連接到 Socket.IO 服務器,并且 Socket.IO 客戶端也將無法連接到普通 WebSocket 服務器。 ``` // WARNING: the client will NOT be able to connect! const socket = io("ws://echo.websocket.org"); ``` > Socket.IO 不適合在移動應用的后臺服務中使用。 Socket.IO 庫與服務器保持開放的 TCP 連接,這可能會導致用戶消耗大量電池。對于此用例,請使用專用消息傳遞平臺(例如[FCM](https://firebase.google.com/docs/cloud-messaging))。 ## 特性 以下是 Socket.IO 通過普通 WebSocket 提供的功能: ### HTTP 長輪詢回退 如果無法建立 WebSocket 連接,連接將回退到 HTTP 長輪詢。 此功能是十多年前創建 Socket.IO 項目時人們使用 Socket.IO 的第一大原因(!),因為瀏覽器對 WebSockets 的支持仍處于起步階段。 即使大多數瀏覽器現在都支持 WebSocket(超過[97%](https://caniuse.com/mdn-api_websocket)),它仍然是一個很棒的功能,因為我們仍然收到用戶的報告,稱他們無法建立 WebSocket 連接,因為他們位于某些配置錯誤的代理后面。 ### 自動重連 在某些特定條件下,服務器和客戶端之間的 WebSocket 連接可能會中斷,而雙方都不知道鏈接的中斷狀態。 這就是 Socket.IO 包含心跳機制的原因,該機制會定期檢查連接的狀態。 當客戶端最終斷開連接時,它會自動以指數回退延遲重新連接,以免服務器不堪重負。 ### 數據包緩沖 當客戶端斷開連接時,數據包會自動緩存,并在重新連接時發送。 更多信息在[此處](https://socket.nodejs.cn/docs/v4/client-offline-behavior/#buffered-events)。 ### 回執 Socket.IO 提供了一種發送事件和接收響應的便捷方法: 發送者 ~~~ socket.emit("hello", "world", (response) => { console.log(response); // "got it"}); ~~~ 接收者 ~~~ socket.on("hello", (arg, callback) => { console.log(arg); // "world" callback("got it");}); ~~~ 你還可以添加超時: ~~~ socket.timeout(5000).emit("hello", "world", (err, response) => { if (err) { // the other side did not acknowledge the event in the given delay } else { console.log(response); // "got it" }}); ~~~ ### 廣播 在服務器端,你可以向[所有連接的客戶端](https://socket.nodejs.cn/docs/v4/broadcasting-events/)或[給一部分客戶端](https://socket.nodejs.cn/docs/v4/rooms/)發送事件: ~~~ // to all connected clientsio.emit("hello");// to all connected clients in the "news" roomio.to("news").emit("hello"); ~~~ 這在[擴展到多個節點](https://socket.nodejs.cn/docs/v4/using-multiple-nodes/)時也有效。 ### 多路復用 命名空間允許你通過單個共享連接拆分應用的邏輯。例如,如果你想要創建只有授權用戶才能加入的 "管理" 通道,這可能會很有用。 ~~~ io.on("connection", (socket) => { // classic users});io.of("/admin").on("connection", (socket) => { // admin users}); ~~~ ## 實戰示例 ### 服務器端 服務器端這里使用`PHPSocket.IO`。PHPSocket.IO是基于Workerman開發的PHP版本的`socket.IO`服務。可用于服務器消息的推送、聊天室、客服系統的開發。 官方文檔:`https://github.com/walkor/phpsocket.io` #### 安裝 ```php composer require workerman/phpsocket.io ``` #### 服務端`server.php` ```php <?php /** * @desc server.php 描述信息 * @author Tinywan(ShaoBo Wan) */ declare(strict_types=1); require_once '../vendor/autoload.php'; use Workerman\Worker; use PHPSocketIO\SocketIO; // 創建socket.io服務端,監聽3120端口 $io = new SocketIO(2024); // 當有客戶端連接時打印一行文字 $io->on('connection', function($socket)use($io){ echo '[x] new connection coming'.PHP_EOL; }); Worker::runAll(); ``` 啟動服務端 ``` php server.php start ``` ![](https://img.kancloud.cn/a8/78/a8785110f4f56a871f6fa84f35ce0d81_999x209.png) ### 客戶端 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>phpsocket.io 客戶端</title> </head> <body> <script src='https://cdn.bootcss.com/socket.io/2.0.3/socket.io.js'></script> <script> var socket = io('http://127.0.0.1:2024'); socket.on('connect', function(){ console.log('connect success'); }); </script> </body> </html> ``` 瀏覽器打開后,服務端輸出 ``` ---------------------------------------------- WORKERMAN ----------------------------------------------- Workerman version:4.1.15 PHP version:7.4.28 ----------------------------------------------- WORKERS ------------------------------------------------ worker listen processes status PHPSocketIO socketIO://0.0.0.0:2024 1 [ok] [x] new connection coming [x] new connection coming [x] new connection coming ``` ## 自定義事件 socket.io主要是通過事件來進行通訊交互的。socket連接除了自帶的`connect`,`message`,`disconnect`三個事件以外,在服務端和客戶端開發者可以自定義其它事件。 服務端和客戶端都通過emit方法觸發對端的事件。例如下面的代碼在服務端定義了一個`chat message`事件,事件參數為`$msg`。 ```php <?php require_once __DIR__ . '/vendor/autoload.php'; use Workerman\Worker; use PHPSocketIO\SocketIO; $io = new SocketIO(2024); // 當有客戶端連接時 $io->on('connection', function($socket)use($io){ // 定義chat message事件回調函數 $socket->on('chat message', function($msg)use($io){ // 觸發所有客戶端定義的chat message from server事件 $io->emit('chat message from server', $msg); }); }); Worker::runAll(); ``` 客戶端通過下面的方法觸發服務端的`chat message`事件。 ``` <script src='//cdn.bootcss.com/socket.io/1.3.7/socket.io.js'></script> <script> // 連接服務端 var socket = io('http://127.0.0.1:2024'); // 觸發服務端的chat message事件 socket.emit('chat message', '這個是消息內容...'); // 服務端通過emit('chat message from server', $msg)觸發客戶端的chat message from server事件 socket.on('chat message from server', function(msg){ console.log('get message:' + msg + ' from server'); }); </script> ``` ## workerStart事件 `phpsocket.io`提供了`workerStart`事件回調,也就是當進程啟動后準備好接受客戶端鏈接時觸發的回調。 一個進程生命周期只會觸發一次。可以在這里設置一些全局的事情,比如開一個新的Worker端口等等。 ``` require_once __DIR__ . '/vendor/autoload.php'; use Workerman\Worker; use PHPSocketIO\SocketIO; $io = new SocketIO(9120); // 監聽一個http端口,通過http協議訪問這個端口可以向所有客戶端推送數據(url類似http://ip:9191?msg=xxxx) $io->on('workerStart', function()use($io) { $inner_http_worker = new Worker('http://0.0.0.0:9191'); $inner_http_worker->onMessage = function($http_connection, $data)use($io){ if(!isset($_GET['msg'])) { return $http_connection->send('fail, $_GET["msg"] not found'); } $io->emit('chat message', $_GET['msg']); $http_connection->send('ok'); }; $inner_http_worker->listen(); }); // 當有客戶端連接時 $io->on('connection', function($socket)use($io){ // 定義chat message事件回調函數 $socket->on('chat message', function($msg)use($io){ // 觸發所有客戶端定義的chat message from server事件 $io->emit('chat message from server', $msg); }); }); Worker::runAll(); ```
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看