Created
February 13, 2021 17:08
-
-
Save leroy/37db9ed598357e3ff25db838ae2bca08 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends Node | |
signal error | |
const PORT = 1337 | |
var client: StreamPeerTCP | |
var stream: PacketPeerStream | |
func _ready(): | |
start() | |
const code = """ | |
const vm = require('vm') | |
const net = require('net') | |
let server = net.createServer(); | |
let context = vm.createContext(); | |
server.on('error', function(error) { | |
console.log(error) | |
}) | |
server.on('connection', function(socket) { | |
console.log('Connection!'); | |
socket.on('error', function() {}) | |
socket.on('data', function(data) { | |
let result; | |
// First 4 bytes of TCP are the length of the packet | |
code = data.slice(4).toString('utf-8') | |
try { | |
result = vm.runInContext(code, context) | |
} catch(error) { | |
console.log(error) | |
socket.write(JSON.stringify({ | |
id: 'error', | |
error: error | |
}), error => console.log(error)) | |
} | |
console.log(result) | |
socket.write(JSON.stringify({ | |
id: 'result', | |
result: JSON.stringify(result) | |
}), error => console.log(error)) | |
}) | |
}); | |
server.listen(%s) | |
""" % [PORT] | |
var pid; | |
func start(): | |
pid = OS.execute("node", ["-e", JavascriptApi._formatCode(code)], true, output) | |
start_connection() | |
func start_connection(): | |
client = StreamPeerTCP.new() | |
client.connect_to_host('127.0.0.1', 1337) | |
stream = PacketPeerStream.new() | |
stream.set_stream_peer(client) | |
func stop(): | |
OS.kill(pid) | |
func eval(code: String): | |
var buffer = code.to_utf8() | |
print_debug(Array(buffer).size()) | |
print_debug(Array(buffer)) | |
stream.put_packet(buffer) | |
var waitForResponse = true | |
while(waitForResponse): | |
if (client.is_connected_to_host() && client.get_available_bytes() > 0): | |
waitForResponse = false | |
var response = JSON.parse(client.get_utf8_string(client.get_available_bytes())).result | |
match response.id: | |
'result': | |
return response.result | |
'error': | |
emit_signal("error", response.error) | |
return null | |
return null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment