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
資料夾。
請參閱文件和範例資料夾
* 這將需要更改協議,因為協議假設資料包是使用可靠、有序的連接發送的
麻省理工學院