Socket.io Client

0 views
Skip to first unread message

Derrick Drescher

unread,
Aug 3, 2024, 3:24:59 PM8/3/24
to foursboudicas

Is there any way to disconnect a client with SocketIO, and literally close the connection? So if someone is connected to my server, and I want to close the connection between them and my server, how would I go about doing that?

An example use case: Client did connect to web socket server with invalid access token (access token handed over to web socket server with connection params). Web socket server notifies the client that it is going to close the connection, because of his invalid access token:

I have using the socket client on React Native app, when I called socketIOClient.disconnect() this disconnects from the server but when I connect to the socket again the previous events were connected again, and the below code works for me by removing all existing events and disconnecting socket conneciton.

I went into the node_modules directory, where I installed socket.io through npm, and inside socket.io/lib/ is socket.io.js file. However, this is server-side (uses the phrase require(), which errors on the client).

The socket.io getting started page isn't clear on this, but I found that the server side of socket.io automatically hosts the .js file on starting node, in the directory specified in the documentation:

A little setup, I have a front end site that is served with express localhost:9200 then I have a back end app localhost:3100 that is also served with express and I am trying to emit events from localhost:9200 to the socket.io server localhost:3100

The issue was with the above of course, because io in the above case for some reason was an object when it should be a function, I came across an old post which mentioned using var socket = io.connect(' :3100'); connect and that worked, I though it was depreciated or something, I have no clue why the docs don't mention this but it fixed my issue.

Starting up the server works fine and running :8080 in my browser also works, returning 'Hello Socket Lover' as expected. But I want to make a different page talk to the sockets, not run one from node.js.

Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).

So, I have been trying to understand Socket.io lately, but I am not a supergreat programmer, and almost every example I can find on the web (believe me I have looked for hours and hours), has extra stuff that complicates things. A lot of the examples do a bunch of things that confuse me, or connect to some weird database, or use coffeescript or tons of JS libraries that clutter things up.

I'd love to see a basic, functioning example where the server just sends a message to the client every 10 seconds, saying what time it is, and the client writes that data to the page or throws up an alert, something very simple. Then I can figure things out from there, add stuff I need like db connections, etc. And yes I have checked the examples on the socket.io site and they don't work for me, and I don't understand what they do.

Edit: I feel it's better for anyone to consult the excellent chat example on the Socket.IO getting started page. The API has been quite simplified since I provided this answer. That being said, here is the original answer updated small-small for the newer API.

The variable names are declared locally rather than all at the top because they are only used in each of the sections between the comments. Each of these could be in a separate file and run as its own node.

If you open up a web browser, and point it to the hostname you're running the node process on, you should see the same numbers appear in your browser, along with any other connected browser looking at that same page.

every simple socket.io example i could find involved http.createServer(). but what if you want to include a bit of socket.io magic in an existing webpage? here is the absolute easiest and smallest example i could come up with.

i hope this very simple example spares my fellow newbies some struggling. and please notice that i stayed away from using "reserved word" looking user-defined variable names for my socket definitions.

The advantage of the simple client is that it abstracts away the logic requiredto maintain a Socket.IO connection. This client handles disconnections andreconnections in a completely transparent way, without adding any complexity tothe application.

By default the client first connects to the server using the long-pollingtransport, and then attempts to upgrade the connection to use WebSocket. Toconnect directly using WebSocket, use the transports argument:

The arguments provided to the method are the name of the event to emit and theoptional data that is passed on to the server. The data can be of type str,bytes, dict, list or tuple. When sending a list or atuple, the elements in it need to be of any allowed types except tuple.When a tuple is used, the elements of the tuple will be passed as individualarguments to the server-side event handler function.

The Socket.IO protocol is event based. When a server wants to communicate witha client it emits an event. Each event has a name, and a list ofarguments. The client registers event handler functions with thesocketio.Client.event() or socketio.Client.on() decorators:

In the first example the event name is obtained from the name of thehandler function. The second example is slightly more verbose, but itallows the event name to be different than the function name or to includecharacters that are illegal in function names, such as spaces.

The connect_error handler is invoked when a connection attempt fails. Ifthe server provides arguments, these are passed on to the handler. The servercan use an argument to provide information to the client regarding theconnection failure.

The disconnect handler is invoked for application initiated disconnects,server initiated disconnects, or accidental disconnects, for example due tonetworking failures. In the case of an accidental disconnection, the client isgoing to attempt to reconnect immediately after invoking the disconnecthandler. As soon as the connection is re-established the connect handler willbe invoked once again.

The client will verify the server certificate by default. To disablecertificate verification, or to use other less common options such as clientcertificates, the client must be initialized with a custom HTTP session objectthat is configured with the desired TLS/SSL options.

When a server emits an event to a client, it can optionally provide acallback function, to be invoked as a way of acknowledgment that the serverhas processed the event. While this is entirely managed by the server, theclient can provide a list of return values that are to be passed on to thecallback function set up by the server. This is achieved simply by returningthe desired values from the handler function:

Likewise, the client can request a callback function to be invoked after theserver has processed an event. The socketio.Server.emit() method has anoptional callback argument that can be set to a callable. If thisargument is given, the callable will be invoked after the server has processedthe event, and any values returned by the server handler will be passed asarguments to this function.

The Socket.IO protocol supports multiple logical connections, all multiplexedon the same physical connection. Clients can open multiple connections byspecifying a different namespace on each. Namespaces use a path syntaxstarting with a forward slash. A list of namespaces can be given by the clientin the connect() call. For example, this example creates two logicalconnections, the default one plus a second connection under the /chatnamespace:

When class-based namespaces are used, any events received by the client aredispatched to a method named as the event name with the on_ prefix. Forexample, event my_event will be handled by a method named on_my_event.If an event is received for which there is no corresponding method defined inthe namespace class, then the event is ignored. All event names used inclass-based namespaces must use characters that are legal in method names.

As a convenience to methods defined in a class-based namespace, the namespaceinstance includes versions of several of the methods in thesocketio.Client and socketio.AsyncClient classes thatdefault to the proper namespace when the namespace argument is not given.

When a client connection to the server is established, a few backgroundtasks will be spawned to keep the connection alive and handle incomingevents. The application running on the main thread is free to do anywork, as this is not going to prevent the functioning of the Socket.IOclient.

However, @bootsie123 and I are thinking this could be a platform issue of some kind, since we were both running Windows 10 and I know both @DavideBarranca and @kerrishotts (who had troubles running the helper sample) are running Mac.

By default io initializes with [ "polling", "websocket" ] as its transports. This means that it will start out with making HTTP requests through polling and then upgrade the connection to websockets if possible.

Looking into this further, it seems it might be an issue with the way Socket.IO sends requests and how UXP handles them. Monitoring localhost with Wireshark reveals that the request itself is failing before it even gets sent. This is particularly weird considering that the URLs are all reachable. Might be something for one of the developers to take a look at in their free time

Second issue I reported is missing WebSocket class is missing static constants for socket status. Those are present only on instance of class but not class itself as static properties. So I had to add them to fix it.

c80f0f1006
Reply all
Reply to author
Forward
0 new messages