Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

UDP-like channels in the browser

NotificationsYou must be signed in to change notification settings

3mcd/web-udp

Repository files navigation

web-udp is a library used to establish unreliable data channels in Node/browser environments. The key goal of this project to provide a small, stable API that anyone can use to work with real-time data on the Web.

The library is currently implemented as an abstraction on top of unordered and unreliable RTCDataChannels. Since WebRTC is a dependency, a WebSocket based signaling server is included with the package to facilitate connections between clients. Client/server connections are available with the help of thewrtc package.

API

Signal<T>.subscribe(subscriber:T=>any)Signal<T>.unsubscribe(subscriber:T=>any)Client(options?:{url?:string})Client.connect(to?:string="__MASTER__",options?:{binaryType?:"arraybuffer"|"blob",maxRetransmits?:number,maxPacketLifeTime?:number,metadata?:any,UNSAFE_ordered?:boolean}):Promise<Connection>Client.route():Promise<string>Client.connections:Signal<Connection>Connection.send(message:any):voidConnection.close():voidConnection.closed:SignalConnection.errors:Signal<{err:string}>Connection.messages:Signal<any>Connection.metadata:any// NodeServer({server:http.Server,keepAlivePeriod?:number=30000})Server.client():ClientServer.connections:Signal<Connection>

Installation

npm i @web-udp/clientnpm i @web-udp/server

Examples

Client/Server

Below is a simple example of a ping server:

// client.jsimport{Client}from"@web-udp/client"asyncfunctionmain(){constudp=newClient()constconnection=awaitudp.connect()connection.send("ping")connection.messages.subscribe(console.log)}
// server.jsconstserver=require("http").createServer()const{ Server}=require("@web-udp/server")constudp=newServer({ server})udp.connections.subscribe(connection=>{connection.messages.subscribe(message=>{if(message==="ping"){connection.send("pong")}})connection.closed.subscribe(()=>console.log("A connection closed."))connection.errors.subscribe(err=>console.log(err))})server.listen(8000)

Metadata

Themetadata option inClient.connect is used to send arbitrary handshake data immediately after establishing a connection. When a new connection is established, the remote client can access this data on themetadata property of the connection object without having to subscribe to the remote client's messages. Handshake metadata is transmitted over a secureRTCDataChannel, making it a good candidate for sensitive data like passwords.

In the below example, a server handles authentication before subscribing to the client's messages:

// client.jsconstconnection=awaitudp.connect({metadata:{credentials:{username:"foo",password:"bar",},},})
// server.jsudp.connections.subscribe(connection=>{letusertry{user=awaitfakeAuth.login(connection.metadata.credentials)}catch(err){// Authentication failed, close connection immediately.connection.send(fakeProtocol.loginFailure())connection.close()return}// The user authenticated successfully.connection.send(fakeProtocol.loginSuccess(user))connection.messages.subscribe(...)})

P2P

web-udp also supports peer-to-peer communication. The below example demonstrates two clients connected in the same browser tab:

<!-- index.html --><scriptsrc="/node_modules/@web-udp/client/dist/index.js"></script><scriptsrc="client.js"></script>
// client.jsasyncfunctionmain(){constleft=newUdp.Client()constright=newUdp.Client()constroute=awaitleft.route()constconnection=awaitright.connect(route)left.connections.subscribe(connection=>connection.messages.subscribe(console.log),)connection.send("HELLO")}
// server.jsconstserver=require("http").createServer()const{ Server}=require("@web-udp/server")Server({ server})server.listen(8000)

Reliability

Client.connect optionally takes the RTCDataChannelmaxPacketLifeTime andmaxRetransmits options. These options can be used to enable an unordered and reliable data channel.

Known Issues

WebSockets are used as the signaling transport. This socket is kept open after the DataChannel is established to forward it's close event (e.g. when a browser tab is closed) in order to terminate hangingweb-udp connections. A keepalive signal is sent periodically to keep the socket open in the case of hosts with connection timeouts. The period at which the keepalive signal is sent can be configured via the server'skeepAlivePeriod option.

License

Copyright 2023 Eric McDaniel

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


[8]ページ先頭

©2009-2025 Movatter.jp