Skip to content

Any way to know if a client connection was dropped/closed? #12

@asiby

Description

@asiby

Hi guys

Nice library. Thanks for this. I am wondering if someone can help me with the following this issue.

I am trying to know when a client connection was dropped. But I can't find any way to do it with this java-express. It is based on what's done in Expressjs. So to help you better understand what I'm trying to achieve, please check the following code that can be used as a GET event handler in Expressjs ... I borrowed it from https://alligator.io/nodejs/server-sent-events-build-realtime-app/#sse-express-backend

function eventsHandler(req, res, next) {
  // Mandatory headers and http status to keep connection open
  const headers = {
    'Content-Type': 'text/event-stream',
    'Connection': 'keep-alive',
    'Cache-Control': 'no-cache'
  };
  res.writeHead(200, headers);

  // After client opens connection send all nests as string
  const data = `data: ${JSON.stringify(nests)}\n\n`;
  res.write(data);

  // Generate an id based on timestamp and save res
  // object of client connection on clients list
  // Later we'll iterate it and send updates to each client
  const clientId = Date.now();
  const newClient = {
    id: clientId,
    res
  };
  clients.push(newClient);

  // When client closes connection we update the clients list
  // avoiding the disconnected one
  req.on('close', () => {
    console.log(`${clientId} Connection closed`);
    clients = clients.filter(c => c.id !== clientId);
  });
}

In this code, please notice the part where we have req.on('close', () => {...}) near the end of the snippet.

This allows listening to events on the request object. It could be a close event, an error event, etc.

I know that the .on() fonction is a Javascript specific function and is probably inherited by the reqobject. But I am hoping that someone could help me achieve the same thing with java-express .

Essentially, I am trying to keep track of each request until they are disconnected. And in the meantime, when I receive a POST request (in my Java code) that will have a channel property in the submitted data, I will send that to all the GET requests that were made with that same channel. I know that clients will stay connected because they are supposed to be using an EventSource() connection to connect to the server, which will in turn a response with a text/event-stream content type.

Thank you

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions