Git Product home page Git Product logo

rpc's Introduction

expose methods between node server and web client

straightforward, functional, room for polish. remote throwing. uses websockets.

now with trans-network callbacks!

eg

server (node)

const ws = require("ws");
const RPC = require("rpc");
const PORT = 41374;

const wss = new ws.Server({ PORT });
wss.on('connection', (socket, req) => {
	initConnection(socket);
};
console.log("Doing a big ol' listen on port", PORT);

let clients = [];

async function initConnection(socket) {
	let name;
	let id = Math.random();

	const client = RPC.init({
		socket,
		onClose: () => {
			clients = clients.filter(c => c !== client);
			clients.forEach(c => c.write(`* ${name} has left`)); // <- call write() on the server, as exposed by its RPC.init()
			delete clients[id];
		},
		methods: { // methods to expose to client
			async say(message) {
				clients.forEach(c => c.write(`<${name}> ${message}`));
			},
		},
	});

	name = await client.requestName();
	clients.forEach(c => c.write(`* ${name} has joined`));

	clients.push(client);
}

client

const RPC = require("rpc");

const protocol = "ws";
const outputElement = document.getElementById("chat-out");
const inputElement = document.getElementById("chat-in");

const socket = new WebSocket(`${protocol}://` + location.hostname + ":" + PORT);
socket.addEventListener("open", event => {
	initConnection(socket);
});

function initConnection(socket){
	const server = RPC.init({
		socket,
		onWarn: err => console.warn("rpc warning:", err),
		onClose: () => delete users[id],
		throwBack: true, // rethrow throws to the remote caller
		methods: { // methods to expose to server
			write: async (s) => outputElement.appendChild(new Text(s + "\n")),
			// remote methods can of course return values:
			requestName: async () => prompt("server is requesting your nickname"),
		},
	});

	inputElement.addEventListener("keypress", event => {
		if (event.key === "Enter"){
			server.say(inputElement.value);
			inputElement.value = "";
		}
	});
}

callback fun

// client
const exposeMethods = {
	doThing: async (num, callback) => {
		if (num < 0)) return callback(null, "too low");
		if (num > 50)) return callback(null, "too high");
		callback(num * 2);
	}
};

// server
const result = client.doThing(6, (result, error) => {
	if (error){
		console.error(error);
	} else {
		console.log("Result:", result);
	}
});
// writes to server console: Result: 12

go wild!

functions can be passed and returned, including as values in arrays and object properties.

// server
const store = {};
const exposeMethods = {
	getStorage: async () => {
		return {
			get: async key => store[key],
			set: async (key, value) => store[key] = value,
		}
	}
};

// client
const storage = await server.getStorage();
const name = await storage.get("name");
await storage.set("thing", 5);

rpc's People

Contributors

tiadrop avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.