logo
down
shadow

How to handle socket.io disconnect by client by leaving page?


How to handle socket.io disconnect by client by leaving page?

By : engineer
Date : November 17 2020, 11:55 AM
it fixes the issue
I have a socket.io application with node.js and was wondering what possibilities exist to respond to a client simply closing their browser window. Is there anyway to know that this has been done? What kinda of signal can been sent to the server?
code :


Share : facebook icon twitter icon
How to handle client disconnect in Socket Programming?

How to handle client disconnect in Socket Programming?


By : Insomnia94
Date : March 29 2020, 07:55 AM
like below fixes the issue Your application crashes, because you throw an exception in the catch block of your method.
If you don't want your application to crash, you need to remove the throw new Exception(ex.Message); line from the catch block. Replace it with code that handles the error and gracefully restores your application to a safe state. From reading your code, this should be done by removing the clientSocket from connectedClients
code :
private void OnReceive(IAsyncResult result)
{
    try
    {
        Socket clientSocket = (Socket)result.AsyncState;
        clientSocket.EndReceive(result);

        command = responseMessage = string.Empty;
        command = ByteToString(receviedData);
        receviedData = new byte[30];

        if (command=="Connect")
        {
            ClientInfo clientInfo = new ClientInfo() {
               socket = clientSocket,
               IP = clientSocket.RemoteEndPoint.ToString(),
               }; 
            connectedClients.Add(clientInfo);
            responseMessage = "Connection established...";
        }
        else if (command=="Disconnect")
        {
            removeClientInfo(clientSocket);
            clientSocket.Close();
        }
        else
        {
            responseMessage = "Error";
        }

        byte[] responseStatus = StringToByte(responseMessage);
        for (int i = 0; i < connectedClients.Count; i++)
        {
            if (connectedClients[i].socket==clientSocket)
            {
                connectedClients[i].socket.BeginSend(responseStatus, 0, responseStatus.Length,SocketFlags.None, new AsyncCallback(OnSend), connectedClients[i].socket);
                break;
            }
        }

    }
    catch(Exception ex)
    {
      // add error handling and gracefully recover
      // caution: The way done here, might work, but it smells :-/
      removeClientInfo((Socket)result.AsyncState);
      ((Socket)result.AsyncState).Close();
    }
}

/// removes the client info from the connectedClients enumerable
private void removeClientInfo(Socket socket)
{
    for (int i = 0; i < connectedClients.Count; i++)
    {
        if (connectedClients[i].socket == socket)
        {
            connectedClients.RemoveAt(i);
            break;
        }
    }
}
NodeJS + Cluster + Socket.io + Redis - iOS not leaving rooms after disconnect

NodeJS + Cluster + Socket.io + Redis - iOS not leaving rooms after disconnect


By : Борис
Date : March 29 2020, 07:55 AM
will be helpful for those in need So I discovered that by using my own methods of reference counting, i can bypass needing socket.io to be accurate. Since i'm already using Redis to back my sockets through pubsub, i just create another client connection to redis and setex the socket.id's on an expiration. When my sockets unsubscribe or disconnect, i delete all the keys in Redis associated with the socket.id. This way, i have an instant snapshot of whos on, and if the key for some reason didn't get deleted on disconnect/unsub, it will expire based on what i set for the setex call.
I'll try and remember to come back in two days to mark my own answer as correct.
SocketIO Disconnect Leaving Socket Listening

SocketIO Disconnect Leaving Socket Listening


By : Waffelei
Date : March 29 2020, 07:55 AM
this will help The problem was caused by the location of my redis.on 'message' listener. I was listenting for that on each and every socket that I created. In reality, I only needed to listen for it in a global sense and then message any rooms. This looks like this:
code :
io.on 'connection', (socket) ->
  log.info "Connection established. [Socket: #{socket.id}]"

  socket.on 'join_room', (roomName) ->
    log.info "Join room '#{roomName}'. [Socket: #{socket.id}]"
    socket.join roomName

  socket.on 'disconnect', ->
    log.info "Connection destroyed. [Socket #{socket.id}]"

redis.on 'message', (redisChannel, message) ->
  message = JSON.parse message
  log.info "Room: #{message.room} - Event: #{message.event} - Message: #{message.message}"
  io.sockets.in(message.room).emit(message.event, message.message)
Java android client socket not getting response until after socket disconnect

Java android client socket not getting response until after socket disconnect


By : Void Ping
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Try adding a \n to the end of the message. Also do not set 'NoDelay` to false. You are doing an asynchronous send.
Socket.io server not receiving 'disconnect' event when client calls disconnect

Socket.io server not receiving 'disconnect' event when client calls disconnect


By : jackchan7808
Date : March 29 2020, 07:55 AM
To fix the issue you can do I think this is a typical synchronicity problem (read explanations in code comments).
code :
// This code will try to connect the server - 
// but the connection process is asynchronous
const mj = ioClient(`https://localhost:${socketPort}`);

// Now you subscribe to the disconnect event which is fine
mj.on('disconnect', () => {
    console.log('mj disconnect');
});

// And now you try to disconnect immediately which is done synchronously
// but how do you want to disconnect since you are still not connected ...
mj.disconnect();
const mj = ioClient(`https://localhost:${socketPort}`);

mj.on('connect', () => {

    // Subscribe to disconnect event once you know you are connected
    mj.on('disconnect', () => {
        console.log('mj disconnect');
    });

    // Now disconnect once you are connected 
    mj.disconnect();
});
Related Posts Related Posts :
  • angular 6 Please add a @NgModule annotation
  • Trying to cast element ID to class selector in jQuery
  • Swipe JS - Display 3 Slides at a time
  • Jasmine test to call function when value is null
  • Redux reducer gets string instead of object
  • Keep chrome javascript running even if page reload
  • The event.target.value is not insert the userinput into a variable
  • Exporting HTML tables to Excel (.xls) in a separate sheet
  • Jquery tooltip on dialog close button
  • access variable inside anonymous function from outside
  • How come func is called from a function?
  • How to change add and remove active class in JavaScript
  • how to toggle a specific div in javascript
  • How to get all the values from multiple keys of an array of object?
  • jQuery bind() unbind() and on() and off()
  • regular expression to find DD Month YYYY from a string
  • How to upload files from web client (HTML/jQuery form) to your Dropbox folder
  • Backbone history and require.js issue
  • Confusion over Classical and Prototypal Inheritance Javascript
  • How to take screen shot of current webpage using Javascript/JQuery?
  • Store meridiem in a variable
  • class declared inside closure vs standard class without closure
  • javascript confirm box always return true
  • dynamically changing the size of font size based on text length using css and html
  • Node.js - Getting the host IP address while on Amazon EC2
  • Confusing CSS, can anyone explain please
  • How to install v8-profiler on Windows 8 (64 bit) using npm?
  • Resolve promise based on another promise
  • google maps adding overlay layer above UI and markers
  • Style specific letter?
  • RangeError: Maximum call stack size exceeded with array.slice
  • node rest client get with local variable
  • If condition not executes while mouse move fastly
  • Count the number of displayed elements in a HTML list
  • Locate JavaScript source code in Emacs
  • Clean, Modular Code vs MV* Frameworks
  • infinite scroll without loading image
  • Backbone: reverse collection order with comparator
  • What do printers ignore?
  • jQuery UI .tabs() Contentless tab?
  • Execute Javascript alert() after page (visually) loaded
  • JavaScript - duplicating array doesn't work
  • Excessive clickable area below image
  • JavaScript Regex: Replace |b| with <b>
  • Unexpected value change in 2D array in JavaScript
  • Function doesnt see parameter as a array of objects
  • jQuery fetch keypress event on chrome and IE
  • How to enable jquery validate localization?
  • Cassandra map collection returned by node.js Helenus looks odd
  • angular ng-repeat with multiple filter options
  • Selecting Children without ID or Class names
  • How to uncheck a group of checkboxes when another checkbox is checked
  • Is hiding content by Javascript or jQuery Worth trying
  • Load XUL resource using javascript
  • XML to HTML text area from server file system
  • set focus() on textbox on form onload
  • es lint '' is assigned a value but never used' eventhough i have used it
  • Can "name" attribute be used for custom VueJS components
  • Get innerHTML of content when it is clicked
  • HTTPS causes CSS animations to not load? Very confused
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org