I can't connect to NodeJS server
Hello.
I cannot get this simple test work. I wrote the client in C++ and the server in NodeJS, both running on my computer. When I execute the client application, the console outputs this text...but the event 'key' is never fired on the server!
Client console output:
Error: No active session [2019-11-21 17:30:11] [connect] Successful connection [2019-11-21 17:30:11] [connect] WebSocket Connection 127.0.0.1:9876 v-2 "WebSocket++/0.8.1" /socket.io/?EIO=4&transport=websocket&t=1574353811 101
¿Anyone knows what am I doing wrong?
Thanks in advance.
C++ client
#include "pch.h"
#include <iostream>
#include <sio_client.h>
using namespace sio;
using namespace std;
int main()
{
sio::client io;
io.connect("http://127.0.0.1:9876");
string command = "w";
io.socket()->emit("key", command );
}
NodeJS server
'use strict';
const express = require('express');
const app = express();
const serverHttp = require('http').Server(app);
const io = require('socket.io')(serverHttp);
const port = 9876;
io.on('connection', function (socket) {
// Never fired :(
socket.on('key', function (data) {
console.log("key received!!!");
});
});
serverHttp.listen(port, function() {
console.log("init!!!");
});
I am also having the same issue. I wrote same sample client code. Do I have to write some listener to get it working ?
I found the solution to this question. Someone helped me out in StackOverflow in my question. it's just u have to use a sleep method or set_open_listener for it to work.
I am posting the StackOverflow thread here. I'm sure it helps. https://stackoverflow.com/questions/59046232/node-js-server-and-c-client-socket-io-connection-not-able-to-emit-or-read-th
For clarification: Basically, your C++ code is emitting before the connection is established.
It would be better to have this workflow:
- Connect from C++ to Node.js
- Have Node.js emit back to C++ that it is ready to receive.
- Emit from C++ to Node.js
This way, you don't have to put an arbitrary sleep() function in your code, and the emit can happen as soon as possible.
Alternatively, you could put the emit() inside a connection listener (e.g., set_open_listener() or set_socket_open_listener()).
As this is not actually a bug, and it appears to be resolved, would you please close the issue so that the other bug reports can receive the necessary attention?
-CP
I created sample app, which sends and receive message from server, over here: https://github.com/harshil1991/socketio-client.cpp_sample
You can take reference from it.