I am using emscripten to port a c++ project into the web, and web application that is going to interact with my C++ code is on NodeJs.
So, I am using Socket.io on Node.js, and I want to use it with my c++ code too, so I went with using a javascript library that uses socket.io code, however it does not seem to work.
I wrote this little example demonstrating this case:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <emscripten.h>
int val = 0;
extern "C"
{
extern void send_board(char* flat_board);
extern bool receive_board(char** _string_dest);
}
void one_iter()
{
#ifdef SEND
char* c = "test";
std::cout << val << std::endl;
if(val%1000 == 0){
send_board(c);
}
val++;
#else
char* c;
if(receive_board(&c)) std::cout << "Received:" << c << std::endl;
#endif
}
int main()
{
emscripten_set_main_loop(one_iter, 0, 1);
return 0;
}
and
mergeInto(LibraryManager.library, {
send_board: function(message) {
socket.on('connect', function(){
socket.emit('game_request_sender_pipeline', {
message: "Hi",
});
});
},
receive_board: function(_string_dest_in_c){
socket.on('connect', function(){
socket.on('game_request_receiver_pipeline' , function (message)
{
var msg = "Other side : " + message.message;
var buffer = Module._malloc(message.message.length + 1);
Module.writeStringToMemory(msg, buffer);
setValue(_string_dest_in_c, buffer, '*');
return true;
});
});
return false;
},
});
and I compiled with the following:
// for the sending test
em++ main.cpp --js-library path_to_js_library.js -o socket.html -DSEND=1
// for the receiving test
em++ main.cpp --js-library path_to_js_library.js -o socket.html
and in Node.Js server code, I have:
io.on('connection', function (socket) {
socket.on('game_request_sender_pipeline' , function (message)
{
console.log("game_request_sender_pipeline on.");
socket.broadcast.emit('game_request_receiver_pipeline', {
message: message.message,
});
console.log("game_request_receiver_pipeline emitted.");
});
});
The result is pretty weird, til I thought that it was not working, I cancel the nodejs server and relaunched it, and then the results popped up in the browsers' console.