anysocket
v0.4.29
多个传输上的抽象网络层,客户端/服务器无关,支持 E2EE
这是一项正在进行的工作,API 可能会发生变化。
AnySocket.Packer
)/dist/anysocket.browser.js
)** http传输是实验性的
信息:二进制 RPC 参数和响应会自动打包/解包( AnySocket.Packer.pack
/ AnySocket.Packer.unpack
)。
查看基准测试
npm install -- save anysocket
或者
< script src =" /dist/anysocket.browser.js " > </ script >
或(如果使用 AnySocketHTTP)
< script src =" @anysocket " > </ script >
以下示例在端口 3000 上启动 Websocket 服务器。
const AnySocket = require ( "anysocket" ) ;
const server = new AnySocket ( ) ;
const PORT = 3000 ;
server . listen ( "ws" , PORT )
. then ( ( ) => {
console . log ( "Listening on port:" , PORT ) ;
} )
. catch ( ( err ) => {
console . error ( "Failed to start server:" , err ) ;
} ) ;
server . on ( "connected" , async ( peer ) => {
console . log ( "Connected" , peer . id ) ;
console . log ( await peer . getSyncedTime ( ) ) // { time: 1674671482107, rtt: 2, offset: 0 }
peer . send ( {
hello : "world"
} ) ;
} ) ;
server . on ( "message" , ( packet ) => {
console . log ( "From:" , packet . peer . id , "Message:" , packet . msg ) ;
} ) ;
server . on ( "disconnected" , ( peer , reason ) => {
console . log ( "Disconnected" , peer . id , "Reason:" , reason ) ;
} ) ;
以下示例连接到端口 3000 上的 Websocket
const AnySocket = require ( "anysocket" ) ;
const client = new AnySocket ( ) ;
const PORT = 3000 ;
client . connect ( "ws" , "127.0.0.1" , PORT )
. then ( ( ) => {
console . log ( "Connected to server" ) ;
} )
. catch ( ( err ) => {
console . error ( "Failed to connect to server:" , err ) ;
} ) ;
// after negotiating the AUTH packet, it will trigger the connect event
client . on ( "connected" , async ( peer ) => {
console . log ( "Connected" , peer . id ) ;
console . log ( await peer . getSyncedTime ( ) ) // { time: 1674671482107, rtt: 2, offset: 0 }
peer . send ( {
hello : "world"
} ) ;
} ) ;
client . on ( "message" , ( packet ) => {
console . log ( "From:" , packet . peer . id , "Message:" , packet . msg ) ;
} ) ;
client . on ( "disconnected" , ( peer , reason ) => {
console . log ( "Disconnected" , peer . id , "Reason:" , reason ) ;
} ) ;
更多内容请参见examples
文件夹。
请参阅文档和示例文件夹
* 这将需要更改协议,因为协议假设数据包是使用可靠、有序的连接发送的
麻省理工学院