36#ifndef _UTILS_JSTCPCLIENT_HXX_
37#define _UTILS_JSTCPCLIENT_HXX_
41#include <emscripten.h>
42#include <emscripten/val.h>
47class JSTcpClient :
private JSHubFeedback
51 enum ConnectionFeedback {
62 JSTcpClient(
CanHubFlow *hflow,
string host,
int port,
63 std::function<
void(ConnectionFeedback)> cb =
nullptr)
65 , callback_(std::move(cb))
67 string script =
"Module.remote_server = '" + host +
"';\n";
68 emscripten_run_script(script.c_str());
72 var net = require(
'net');
74 'Connecting to ' + Module.remote_server +
": " + $0);
75 var c = net.connect($0, Module.remote_server, function() {
76 console.log(
'connected to hub: ' + c);
77 c.setEncoding(
'utf-8');
80 var client_port =
new Module.JSHubPort(
81 $1, function(data) { c.write(data); }, $2);
82 c.on(
'close', function() {
83 console.log(
'connection lost');
84 client_port.fb_close();
85 client_port.abandon();
87 c.on(
'error', function(err) {
88 console.log(
'connection error -- disconnected');
89 client_port.fb_error(err.toString());
90 client_port.abandon();
92 c.on(
'data', function(data) { client_port.recv(data); });
94 c.on(
'error', function(err) {
95 console.log(
'Failed to connect.');
96 Module.JSHubFeedback.call_on_error($2, err.toString());
99 port, (
unsigned long)canHub_, (
unsigned long)((JSHubFeedback*)
this));
111 void on_open()
override
117 callback_(CONNECTION_UP);
122 void on_close()
override
128 callback_(CONNECTION_DOWN);
133 void on_error(
string error)
override
135 LOG(
INFO,
"%s", error.c_str());
139 callback_(CONNECTION_ERROR);
144 bool connected_ =
false;
145 std::function<void(ConnectionFeedback)> callback_;
#define LOG(level, message...)
Conditionally write a message to the logging output.
static const int INFO
Loglevel that is printed by default, reporting some status information.