Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Connection Listener on client side #432

Open
PedroCorcaque opened this issue Oct 2, 2024 · 0 comments
Open

Connection Listener on client side #432

PedroCorcaque opened this issue Oct 2, 2024 · 0 comments

Comments

@PedroCorcaque
Copy link

Hi everyone,

I'm using the socket.io-client-cpp library to communicate with a NodeJS server. While the API is very helpful, I'm encountering an issue with detecting server disconnections.

Question:
Is there a way for the client to detect when the server goes down?

My server operates in broadcasting mode (emitting events to all connected clients), so I'm unable to use acknowledgment logic to verify if an event emitted by the client reaches the server.

Here's the situation: When I start both the client and server, communication works as expected. However, if I stop the server, the client continues emitting events (e.g., emitMissionFinish) without realizing the server is down. I tried using client.set_close_listener, client.set_fail_listener, and currentSocket->on_error, but none seem to catch the disconnection.

What I need:
Is there a reliable method to detect if the server goes down after the communication has already been established? The problem I'm facing is that the client keeps sending events, which creates a buffer that, in my case, causes synchronization issues.

Here's a simplified version of my implementation to demonstrate what I'm trying to achieve:

C++ Client-Side

#include <iostream>
#include <thread>
#include <atomic>
#include <sio_client.h>
#include <sio_socket.h>

class Connection
{
private:
    sio::client client;
    sio::socket::ptr currentSocket;
    std::atomic<bool> isConnected;
public:
    Connection() : isConnected(false)
    {
        // Set the open listener before connecting
        client.set_open_listener([this]() {
            std::cout << "Connected to the server!" << std::endl;
            currentSocket = client.socket();
            isConnected = true;

            this->onMissionPaused(); 

        });

        // Set fail listener to capture connection failures
        client.set_fail_listener([this]() {
            std::cerr << "Failed to connect to the server!" << std::endl;
            isConnected = false;
        });

        // Now connect to the Socket.IO server
        client.connect("http://localhost:3000/");
    }

    void onMissionPaused() {
    // Useless for this example
    }

    void emitMissionFinish()
    {
        if (isConnected && currentSocket) {
            std::cout << "Emit event missionFinish" << std::endl;
            sio::message::list theMessage = sio::string_message::create("mission was terminated");

            currentSocket->emit("missionFinish", theMessage, [&](sio::message::list const& ack_resp) {
                if (ack_resp.size() > 0) 
                {
                    std::cout << "Acknowledgment from server: " << ack_resp.at(0)->get_string() << std::endl;
                } 
            });
        } else {
            std::cerr << "Cannot emit event, not connected to server!" << std::endl;
        }
    }
};

int main()
{
    Connection conn;

    while (true)
    {
        conn.emitMissionFinish();
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }

    return 0;
}

NodeJS Server-Side

import express from 'express';
import { createServer } from 'node:http';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import Server from 'socket.io';
import cors from 'cors';

const app = express();
app.use(cors());
const server = createServer(app);
const io = new Server(server);

const __dirname = dirname(fileURLToPath(import.meta.url));

app.get('/', (req, res) => {
	res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
	console.log('A client connected');

	socket.on('missionFinish', (msg, ack) => {
		console.log('Mission Finish event: ', msg);
		if (ack)
		{
			ack("Server received missionFinish");
		}
	});

	socket.on('missionPaused', (msg) => {
		console.log('Mission Paused: ' + msg);
		io.emit('missionPaused', msg);
	});
  
	socket.on('disconnect', () => {
	  	console.log('Client disconnected');
	});
  });

server.listen(3000, '0.0.0.0', () => {
	console.log('server is running at http://0.0.0.0:3000');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant