客戶端安裝
最新版本目前為 4.7.5
,於 2024 年 3 月發布。
您可以在 這裡 找到版本說明。
版本相容性
以下是伺服器與 JS 客戶端之間的相容性表格
JS 客戶端版本 | Socket.IO 伺服器版本 | |||
---|---|---|---|---|
1.x | 2.x | 3.x | 4.x | |
1.x | 是 | 否 | 否 | 否 |
2.x | 否 | 是 | 是1 | 是1 |
3.x | 否 | 否 | 是 | 是 |
4.x | 否 | 否 | 是 | 是 |
[1] 是,搭配 allowEIO3: true
請查看相關的遷移指南
瀏覽器支援
Socket.IO 支援 IE9 以上版本。不再支援 IE 6/7/8。
瀏覽器相容性感謝優秀的 Sauce Labs 平台進行測試
安裝
獨立建置
預設情況下,Socket.IO 伺服器會在 /socket.io/socket.io.js
公開一個用戶端套件。
io
將會註冊為全域變數
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
</script>
如果您不需要這個(請參閱以下其他選項),您可以在伺服器端停用此功能
const { Server } = require("socket.io");
const io = new Server({
serveClient: false
});
來自 CDN
您也可以從 CDN 包含用戶端套件
<script src="https://cdn.socket.io/4.7.5/socket.io.min.js" integrity="sha384-2huaZvOR9iDzHqslqwpR87isEmrfxqyWOF7hr7BY6KG0+hVKLoEXMPUJw3ynWuhO" crossorigin="anonymous"></script>
Socket.IO 也可從其他 CDN 取得
- cdnjs: https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.5/socket.io.min.js
- jsDelivr: https://cdn.jsdelivr.net/npm/socket.io-client@4.7.5/dist/socket.io.min.js
- unpkg: https://unpkg.com/socket.io-client@4.7.5/dist/socket.io.min.js
有幾個套件可用
名稱 | 大小 | 說明 |
---|---|---|
socket.io.js | 34.7 kB gzip | 未壓縮版本,包含 debug |
socket.io.min.js | 14.7 kB min+gzip | 正式版本,不含 debug |
socket.io.msgpack.min.js | 15.3 kB min+gzip | 正式版本,不含 debug,並包含 msgpack parser |
這個 debug 套件允許將偵錯資訊印出至主控台。您可以在 這裡 找到更多資訊。
在開發期間,我們建議使用 socket.io.js
套件。透過設定 localStorage.debug = 'socket.io-client:socket'
,用戶端接收到的任何事件都會印出至主控台。
對於正式環境,請使用 socket.io.min.js
套件,這是個最佳化建置,不包含 debug 套件。
從 NPM
Socket.IO 客户端與打包器相容,例如 webpack 或 browserify。
- NPM
- Yarn
- pnpm
npm install socket.io-client
yarn add socket.io-client
pnpm add socket.io-client
也可以從 Node.js 執行客户端。
注意:由於上述原因,您可能想要從瀏覽器套件中排除偵錯。使用 webpack 時,您可以使用 webpack-remove-debug。
TypeScript 使用者注意:類型現在包含在 socket.io-client
套件中,因此不再需要 @types/socket.io-client
中的類型,而且實際上可能會造成錯誤
Object literal may only specify known properties, and 'extraHeaders' does not exist in type 'ConnectOpts'
其他
相依性樹
客户端的基本安裝包含 9 個套件,其中 5 個由我們的團隊維護
└─┬ socket.io-client@4.7.2
├── @socket.io/component-emitter@3.1.0
├─┬ debug@4.3.4
│ └── ms@2.1.2
├─┬ engine.io-client@6.5.2
│ ├── @socket.io/component-emitter@3.1.0 deduped
│ ├── debug@4.3.4 deduped
│ ├── engine.io-parser@5.2.1
│ ├─┬ ws@8.11.0
│ │ ├── UNMET OPTIONAL DEPENDENCY bufferutil@^4.0.1
│ │ └── UNMET OPTIONAL DEPENDENCY utf-8-validate@^5.0.2
│ └── xmlhttprequest-ssl@2.0.0
└─┬ socket.io-parser@4.2.4
├── @socket.io/component-emitter@3.1.0 deduped
└── debug@4.3.4 deduped
遞移版本
engine.io-client
套件提供負責管理低階連線(HTTP 長輪詢或 WebSocket)的引擎。另請參閱:運作方式
socket.io-client 版本 | engine.io-client 版本 | ws 版本1 |
---|---|---|
4.7.x | 6.5.x | 8.11.x |
4.6.x | 6.4.x | 8.11.x |
4.5.x | 6.2.x | 8.2.x |
4.4.x | 6.1.x | 8.2.x |
4.3.x | 6.0.x | 8.2.x |
4.2.x | 5.2.x | 7.4.x |
4.1.x | 5.1.x | 7.4.x |
4.0.x | 5.0.x | 7.4.x |
3.1.x | 4.1.x | 7.4.x |
3.0.x | 4.0.x | 7.4.x |
2.5.x | 3.6.x | 7.4.x |
2.4.x | 3.5.x | 7.4.x |
[1] 僅限 Node.js 使用者。在瀏覽器中,使用原生 WebSocket API。