Creates a new AnySocket instance
Unique identifier (UUIDv4) that will be used for all connections originating this instance (client/server)
See: AnyHTTPRouter
Alias for AnySocket.listen()
Attaches a new server transport based on the selected *scheme
Arguments:
scheme
- one of the implemented transportsoptions
- one of the options belowport
- port numberjson
{
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
Connects to AnySocket Server
Arguments:
scheme
- one of the implemented transportsip
- server ipport
- server portoptions
- 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);
});
Stops all servers and disconnects all peers
Returns a Promise that resolves/rejects when finished
You can overwrite this function to implement a custom auth validation. Arguments:
packet
- A JSON containing the Peer AnySocket.id and the custom AnySocket.authPacket
Returns true/false if validation passed or not
note: onAuth must be implemented in both server & client
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
Broadcasts a message to all connected peers
Arguments:
message
- a JSON stringifiable objectawaitReply
- 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
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
}
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
note: returns true for proxies
Returns true/false
if AnySocket has a peer with the id
note: returns false for proxies
Returns true/false
if AnySocket has a direct peer (no proxy) with the id
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
Emitted when the link has been established and it's ready for sending/receiving messages
Arguments:
peer
- AnyPeer instance
Emitted when a message is received
Arguments:
packet
- AnyPacket instance
Emitted when the link has been end-to-end encrypted and it's ready to be used
Arguments:
peer
- AnyPeer instance
Emitted when a peer has disconnected
Arguments:
peer
- AnyPeer instancereason
- a string detailing the disconnect reason
Constructor should not be used directly
An incremental unique identifier per packet per peer (used internally)
An AnyPeer instance
An object that contains data sent/received from a peer
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
Packs the bytes
Arguments:
bytes
- Buffer/TypedArray
Returns a string representation of the bytes
Unpacks the bytes
Arguments:
bytes
- String representation of a Buffer/TypedArray
Returns a Buffer/TypedArray
Constructor should not be used directly
Unique peer identifier (UUIDv4) - Peer AnySocket.id
Unique connection identifier (UUIDv4), used internally before getting a AnyPeer.id
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
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
Sends a message to the peer
Arguments:
message
- a JSON stringifiable objectawaitReply
- set to true if a reply is expected (optional) - default: falsetimeout
- 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
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
}
Disconnects the peer
Arguments:
reason
- a string that explains why the peer was disconnected
Returns true
if the AnyPeer instance is a proxy (see: AnySocket.proxy)
Returns true
if the connection has been end-to-end encrypted (see: AnyPeer.e2e)
Emitted when a message is received
Arguments:
packet
- AnyPacket instance
Emitted when the link has been end-to-end encrypted and it's ready to be used
Arguments:
peer
- AnyPeer instance
Emitted when the peer has disconnected
Arguments:
peer
- AnyPeer instancereason
- a string detailing the disconnect reason
Constructor should not be used directly
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 methodpath
- HTTP path, can be a string or RegExp instancecallback
- executed when the path matches a HTTP Path (arguments: AnyHTTPPeer)
Serves static files with Content-Type based on the extension of the file.
Arguments:
url
- url pathdirectory
- 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
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 instancecallback
- executed when the path matches a HTTP Path (arguments: AnyHTTPPeer)
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 instancecallback
- executed when the path matches a HTTP Path (arguments: AnyHTTPPeer)
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 instancecallback
- executed when the path matches a HTTP Path (arguments: AnyHTTPPeer)
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 instancecallback
- executed when the path matches a HTTP Path (arguments: AnyHTTPPeer)
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)
Executes when a HTTP error is catched.
Arguments:
callback
- an error callback (arguments: AnyHTTPPeer, error)
Constructor should not be used directly
Returns the HTTP Path without query string
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
}
Returns the HTTP Cookies
Sets the return status code
Arguments:
code
- HTTP Status code (int)
Returns AnyHTTPPeer for chaining
Sets a header
Arguments:
name
- header name (string)value
- header value (string)
Returns AnyHTTPPeer for chaining
Appends a chunk(part) of the return body
Arguments:
chunk
- HTTP Body (string)
Returns AnyHTTPPeer for chaining
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
Sets a cookie with key and expires = 1
Arguments:
key
- cookie name (string)
Returns AnyHTTPPeer for chaining
Serves a static file. Content-Type is autodetected from the extension
Arguments:
path
- path to filecontentType
- optional custom Content-Type
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",
Flush data and close the connection
Check if the connection has already been ended / closed.