socket.io介绍
Socket.IO 是一个库,可以在客户端和服务器之间实现低延迟、双向和基于事件的通信。它建立在 WebSocket 协议之上,并提供额外的保证,例如回退到 HTTP 长轮询或自动重新连接。
几种可用的 Socket.IO 服务器实现:
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
客户端实现:
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
Python:https://github.com/miguelgrinberg/python-socketio
.Net:https://github.com/doghappy/socket.io-client-csharp
Server (based on websocket的例子):
import { WebSocketServer } from "ws";
const server = new WebSocketServer({ port: 3000 });
server.on("connection", (socket) => {
// send a message to the client
socket.send(JSON.stringify({
type: "hello from server",
content: [ 1, "2" ]
}));
// receive a message from the client
socket.on("message", (data) => {
const packet = JSON.parse(data);
switch (packet.type) {
case "hello from client":
// ...
break;
}
});
});
Client:
const socket = new WebSocket("ws://localhost:3000");
socket.addEventListener("open", () => {
// send a message to the server
socket.send(JSON.stringify({
type: "hello from client",
content: [ 3, "4" ]
}));
});
// receive a message from the server
socket.addEventListener("message", ({ data }) => {
const packet = JSON.parse(data);
switch (packet.type) {
case "hello from server":
// ...
break;
}
});
基于Socket.IO的例子:
import { Server } from "socket.io";
const io = new Server(3000);
io.on("connection", (socket) => {
// send a message to the client
socket.emit("hello from server", 1, "2", { 3: Buffer.from([4]) });
// receive a message from the client
socket.on("hello from client", (...args) => {
// ...
});
});
import { io } from "socket.io-client";
const socket = io("ws://localhost:3000");
// send a message to the server
socket.emit("hello from client", 5, "6", { 7: Uint8Array.from([8]) });
// receive a message from the server
socket.on("hello from server", (...args) => {
// ...
});
这两个示例看起来非常相似,但实际上 Socket.IO 提供了附加功能,这些功能隐藏了在生产环境中运行基于 WebSockets 的应用程序的复杂性。
Features特点:Here are the features provided by Socket.IO over plain WebSockets:
- HTTP long-polling fallback
- Automatic reconnection
- Packet buffering
- Acknowledgements
- Broadcasting
- Multiplexing
Socket.io与websocket的不同:尽管 Socket.IO 确实在可能的情况下使用 WebSocket 进行传输,但它为每个数据包添加了额外的元数据。 这就是为什么 WebSocket 客户端将无法成功连接到 Socket.IO 服务器,而 Socket.IO 客户端也将无法连接到普通 WebSocket 服务器。
Socket.IO 不能在移动应用程序的后台服务中使用。Socket.IO 库保持与服务器的开放 TCP 连接,这可能会导致用户消耗大量电池。 请为此用例使用 FCM 等专用消息传递平台。