Skip to content

Latest commit

 

History

History

docs

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Api

Documentation

AnySocket()

Creates a new AnySocket instance

back to top


AnySocket.id

Unique identifier (UUIDv4) that will be used for all connections originating this instance (client/server)

back to top


AnySocket.http

See: AnyHTTPRouter

back to top


AnySocket.server(scheme, options)

Alias for AnySocket.listen()

back to top


AnySocket.listen(scheme, options)

Attaches a new server transport based on the selected *scheme

Arguments:

  • scheme - one of the implemented transports
  • options - one of the options below
    • port - port number
    • json
{
    ip: "0.0.0.0", // listening ip
    port: 3000, // listening port
    authTimeout: 5 * 1000, // auth timeout
    e2eTimeout: 5 * 1000, // e2e timeout
    replyTimeout: 30 * 1000, // reply timeout
    heartbeatInterval: 5 * 1000 // heartbeat interval
}

Returns a Promise that resolves/rejects when the server has started listening or when it throws an error

back to top


AnySocket.connect(scheme, ip, port, [options])

Connects to AnySocket Server

Arguments:

  • scheme - one of the implemented transports
  • ip - server ip
  • port - server port
  • options - options json
{
    authTimeout: 5 * 1000, // auth timeout
    e2eTimeout: 5 * 1000, // e2e timeout
    replyTimeout: 30 * 1000, // reply timeout
    heartbeatInterval: 5 * 1000 // heartbeat interval
}

Returns a Promise that resolves/rejects when a connection has been established

client.connect("ws", "127.0.0.1", 3000).then(peer => {
    console.log("Connection established to peer", peer.id);
    peer.send("Hello World");
}).catch(reason => {
    console.log("Couldn't connect! Reason:", reason);
});

With cookies support: (WebSocket only)

client.connect("ws", "127.0.0.1", 3000, {
    cookies: {
        "hello": "world"
    }
}).then(peer => {
    console.log("Connection established to peer", peer.id);
    peer.send("Hello World");
}).catch(reason => {
    console.log("Couldn't connect! Reason:", reason);
});

back to top


AnySocket.stop()

Stops all servers and disconnects all peers

Returns a Promise that resolves/rejects when finished

back to top


AnySocket.onAuth(packet)

You can overwrite this function to implement a custom auth validation. Arguments:

Returns true/false if validation passed or not

note: onAuth must be implemented in both server & client

back to top


AnySocket.authPacket()

You can overwrite this function to implement a custom auth packet.

Returns a JSON containing the AUTH packet that will be validated in AnySocket.onAuth()

note: auth packet must be implemented in both server & client

back to top


AnySocket.broadcast(message, [awaitReply])

Broadcasts a message to all connected peers

Arguments:

  • message - a JSON stringifiable object
  • awaitReply - set to true if a reply is expected (optional) - default: false

Returns a Promise that resolves with a AnyPacket if waiting for a reply or rejects on error

note: it doesn't resolve if awaitReply is not set

back to top


AnySocket.setRPC(rpc)

This sets the RPC functions on the AnySocket object so they can be called using AnyPeer.rpc RPC object can be nested indefinitely, but the "this" object will always be the called method's parent. The last param of the RPC function will always be an AnyPeer object.

Each RPC function can return a value, object, Buffer/TypedArray or a Promise (awaits the promise to be resolved)

Binary info:

  • If a RPC receives an argument as a Buffer/TypedArray it will be auto unpacked
  • If a RPC returns a Buffer/TypedArray it will be auto packed

Arguments:

  • rpc - object or class with RPC functions

Any throwed error / reject will be sent back to the client in the form:

{
    error: "error message",
    details: "details",
    code: 500
}

back to top


AnySocket.canProxy(peerID, otherPeerID)

Checks if peerID can be proxied through otherPeerID. Defaults to: false

note: You need to override this function in order to allow proxying

Returns true/false

back to top


AnySocket.hasPeer(id)

note: returns true for proxies

Returns true/false if AnySocket has a peer with the id

back to top


AnySocket.hasDirectPeer(id)

note: returns false for proxies

Returns true/false if AnySocket has a direct peer (no proxy) with the id

back to top


AnySocket.proxy(peerID, throughPeerID)

Send a proxy request for peerID via throughPeerID as relay

note: A proxied peer uses the same flow as a new connection

Returns a Promise that resolves with a AnyPeer or rejects if proxy fails

back to top


AnySocket event connected

Emitted when the link has been established and it's ready for sending/receiving messages

Arguments:

back to top


AnySocket event message

Emitted when a message is received

Arguments:

back to top


AnySocket event e2e

Emitted when the link has been end-to-end encrypted and it's ready to be used

Arguments:

back to top


AnySocket event disconnected

Emitted when a peer has disconnected

Arguments:

  • peer - AnyPeer instance
  • reason - a string detailing the disconnect reason

back to top


AnyPacket()

Constructor should not be used directly

back to top


AnyPacket.seq

An incremental unique identifier per packet per peer (used internally)

back to top


AnyPacket.peer

An AnyPeer instance

back to top


AnyPacket.msg

An object that contains data sent/received from a peer

back to top


AnyPacket.reply(message)

Sends a reply to the current packet

Arguments:

  • message - a JSON stringifiable object

note: you can only reply to a normal message, you cannot reply to a reply packet. It fails silently

back to top


AnySocket.Packer.pack(bytes)

Packs the bytes

Arguments:

  • bytes - Buffer/TypedArray

Returns a string representation of the bytes

back to top


AnySocket.Packer.unpack(bytes)

Unpacks the bytes

Arguments:

  • bytes - String representation of a Buffer/TypedArray

Returns a Buffer/TypedArray

back to top


AnyPeer()

Constructor should not be used directly

back to top


AnyPeer.id

Unique peer identifier (UUIDv4) - Peer AnySocket.id

back to top


AnyPeer.connectionID

Unique connection identifier (UUIDv4), used internally before getting a AnyPeer.id

back to top


AnyPeer.rpc(...args)

This is a special Proxy Object that can indefinitely nested and have any number of arguments, but the last param of the RPC function will always be an AnyPeer object. (the current peer than ran the RPC)

Example: peer.rpc.hello.world.user("LynxAegon")

  • This will try to run a RPC on the peer and the RPC object should look like this:
AnySocket.setRPC({
    hello: {
        world: {
            user: (name, peer) => {
                return new Promise((resolve, reject) => {
                    resolve("Hello World, " + name);
                });
            }
        }
    }
})

Returns a Promise that will resolve if success or reject in case of error

back to top


AnyPeer.e2e()

Enables E2E encryption using ECDH for exchange and then switches to AES-256-CBC with forward secrecy.

Each message is encrypted with a different key derrived from the master key

back to top


AnyPeer.send(message, [awaitReply, [timeout]])

Sends a message to the peer

Arguments:

  • message - a JSON stringifiable object
  • awaitReply - set to true if a reply is expected (optional) - default: false
  • timeout - set a custom reply packet timeout in milliseconds (optional)

Returns a Promise that resolves with a AnyPacket if waiting for a reply or rejects on error

note: it doesn't resolve if awaitReply is not set

note: you can only reply to a normal message, you cannot reply to a reply packet. It fails silently

back to top


AnyPeer.getSyncedTime([refresh])

Uses NTP to sync the time between peers.

  • First call runs a RPC on the peer and caches the rtt and offset.
  • Subsequent calls are returned from cache.

Arguments:

  • refresh - force a refresh

Returns a Promise that resolves with an object like

{ 
    time: 1674671482109, // current time: Date.now() + offset  
    rtt: 2, // round-trip time
    offset: 0 // clock offset
}

back to top


AnyPeer.disconnect(reason)

Disconnects the peer

Arguments:

  • reason - a string that explains why the peer was disconnected

back to top


AnyPeer.isProxy()

Returns true if the AnyPeer instance is a proxy (see: AnySocket.proxy)

back to top


AnyPeer.isE2EEnabled()

Returns true if the connection has been end-to-end encrypted (see: AnyPeer.e2e)

back to top


AnyPeer event message

Emitted when a message is received

Arguments:

back to top


AnyPeer event e2e

Emitted when the link has been end-to-end encrypted and it's ready to be used

Arguments:

back to top


AnyPeer event disconnected

Emitted when the peer has disconnected

Arguments:

  • peer - AnyPeer instance
  • reason - a string detailing the disconnect reason

back to top


AnyHTTPRouter()

Constructor should not be used directly

back to top


AnyHTTPRouter.on(method, path, callback)

Raw method to link to a HTTP query.

Example:

AnySocket.http.on("GET", "/index", (peer) => {
    peer
        .status(200)
        .body("hello world")
        .end();
});

Arguments:

  • method - GET/POST/DELETE/Any Custom Method. Use "_" for any method
  • path - HTTP path, can be a string or RegExp instance
  • callback - executed when the path matches a HTTP Path (arguments: AnyHTTPPeer)

back to top


AnyHTTPRouter.static(url, [directory])

Serves static files with Content-Type based on the extension of the file.

Arguments:

  • url - url path
  • directory - optional directory to serve from, if not set it will use the url (adding ./)

Example:

// http://localhost/static_files/index.html
server.http.static("/static_files"); // resolves to ./static_files/*

// http://localhost/static_files/index.html
server.http.static("static_files"); // resolves to ./static_files/*

// http://localhost/static/index.html
server.http.static("/static", "./static_files"); // resolves to ./static_files/*

// http://localhost/hello
server.http.get("/hello", (peer) => {
    // serves a single static file
    peer.serveFile("./static_files/index.html");
})

See supported Content-Types

back to top


AnyHTTPRouter.any(path, callback)

Matches a path with any method

Example:

AnySocket.http.any("/index", (peer) => {
    peer
        .status(200)
        .body("hello world")
        .end();
});

Arguments:

  • path - HTTP path, can be a string or RegExp instance
  • callback - executed when the path matches a HTTP Path (arguments: AnyHTTPPeer)

back to top


AnyHTTPRouter.get(path, callback)

Matches a path with GET method

Example:

AnySocket.http.get("/index", (peer) => {
    peer
        .status(200)
        .body("hello world")
        .end();
});

Arguments:

  • path - HTTP path, can be a string or RegExp instance
  • callback - executed when the path matches a HTTP Path (arguments: AnyHTTPPeer)

back to top


AnyHTTPRouter.post(path, callback)

Matches a path with POST method

Example:

AnySocket.http.post("/index", (peer) => {
    peer
        .status(200)
        .body("hello world")
        .end();
});

Arguments:

  • path - HTTP path, can be a string or RegExp instance
  • callback - executed when the path matches a HTTP Path (arguments: AnyHTTPPeer)

back to top


AnyHTTPRouter.delete(path, callback)

Matches a path with DELETE method

Example:

AnySocket.http.delete("/index", (peer) => {
    peer
        .status(200)
        .body("hello world")
        .end();
});

Arguments:

  • path - HTTP path, can be a string or RegExp instance
  • callback - executed when the path matches a HTTP Path (arguments: AnyHTTPPeer)

back to top


AnyHTTPRouter.upgrade(callback)

Matches connection upgrade

Example:

AnySocket.http.upgrade((peer) => {
    if(peer.cookies.hello != "world")
        peer.end(); // denies connection upgrade
});

Arguments:

  • callback - executed when the connection is upgraded to WS (arguments: AnyHTTPPeer)

back to top


AnyHTTPRouter.error(callback)

Executes when a HTTP error is catched.

Arguments:

  • callback - an error callback (arguments: AnyHTTPPeer, error)

back to top


AnyHTTPPeer()

Constructor should not be used directly

back to top


AnyHTTPPeer.url

Returns the HTTP Path without query string

back to top


AnyHTTPPeer.query

Returns an object like

{
    headers: req.headers, // headers
    cookies: req.headers.cookie, // cookies
    method: req.method.toLowerCase(), // method lowercased
    body: req.body, // post body
    qs: qs.query // query string
}

back to top


AnyHTTPPeer.cookies

Returns the HTTP Cookies

back to top


AnyHTTPPeer.status(code)

Sets the return status code

Arguments:

  • code - HTTP Status code (int)

Returns AnyHTTPPeer for chaining

back to top


AnyHTTPPeer.header(name, value)

Sets a header

Arguments:

  • name - header name (string)
  • value - header value (string)

Returns AnyHTTPPeer for chaining

back to top


AnyHTTPPeer.body(chunk)

Appends a chunk(part) of the return body

Arguments:

  • chunk - HTTP Body (string)

Returns AnyHTTPPeer for chaining

back to top


AnyHTTPPeer.setCookie(key, value, [expires])

Sets a cookie with key, value and expires.

Cookies are set on the same domain and path "/"

Arguments:

  • key - cookie name (string)
  • value - cookie value (string)
  • expires - cookie expire time (UnixTimestamp in millis). If not set, expires = 1

Returns AnyHTTPPeer for chaining

back to top


AnyHTTPPeer.deleteCookie(key)

Sets a cookie with key and expires = 1

Arguments:

  • key - cookie name (string)

Returns AnyHTTPPeer for chaining

back to top


AnyHTTPPeer.serveFile(path, [contentType])

Serves a static file. Content-Type is autodetected from the extension

Arguments:

  • path - path to file
  • contentType - optional custom Content-Type

Supported Content-Types:

    txt: "text/plain;charset=utf-8",
    html: "text/html;charset=utf-8",
    htm: "text/html;charset=utf-8",
    css: "text/css;charset=utf-8",
    js: "text/javascript;charset=utf-8",
    md: "text/markdown;charset=utf-8",
    sh: "application/x-shellscript;charset=utf-8",
    svg: "image/svg+xml;charset=utf-8",
    xml: "text/xml;charset=utf-8",

    png: "image/png",
    jpeg: "image/jpeg",
    jpg: "image/jpeg",
    jpe: "image/jpeg",
    gif: "image/gif",

    ttf: "font/ttf",
    woff: "font/woff",
    woff2: "font/woff2",
    eot: "application/vnd.ms-fontobject",

    gz: "application/gzip",
    bz: "application/x-bzip",
    bz2: "application/x-bzip2",
    xz: "application/x-xz",
    zst: "application/zst",

back to top


AnyHTTPPeer.end()

Flush data and close the connection

back to top


AnyHTTPPeer.isClosed()

Check if the connection has already been ended / closed.

back to top