简体   繁体   中英

How can I write data to the client connected to a Node.js socket server from another function?

I'm attempting to make a function that would allow for triggering a script in a V8 instance of Node from a node-chakracore instance. I'm doing this by running a newer version of Node as a child process. I want to do this in a way that it only has 1 newer Node instance instead of creating another one for every script I want to run. I want to have a runV8Script function that would trigger the script on the V8 side. The way that I'm wanting to trigger scripts is by having an IPC socket, the server side being Chakra and the client side being V8.

The issue that I'm having is that I can't think of how I could use client outside of the server callback which means I can't have a function send data.

I'm just creating this server with the simple code below, nothing fancy

let server = net.createServer(client => {
    // The client can only be used inside of this callback
});

I'm attempting to make a function that would allow for triggering a script in a V8 instance of Node from a node-chakracore instance. [...] The way that I'm wanting to trigger scripts is by having an IPC socket, the server side being Chakra and the client side being V8.

The general rule of thumb is: clients trigger events in servers, not the other way round.

Luckily for you, this is perfectly possible, since Node is a server, and it can send requests to other servers. So you can have the Node-Chakracore instance running in a server role with respect to the actual requests you want to serve, and at the same time act in a client role towards the Node-V8 instance (which is running on a different port) by sending requests there.

You can either start the Node-V8 instance separately by hand, or you can have it be started as a child process by the Node-Chakracore instance (on startup). Either way, the two instances would talk to each other via a socket (HTTP or other, your choice).

A bit more detail, in case it isn't obvious: For the Chakra instance, you'd write a handler that sends a request to the V8 instance, and that second request gets a completion handler that optionally processes its result and hands it off to the first request's completion handler. (So this is all very similar conceptually to processing a database request or similar; the "database" just so happens to be another Node instance.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM