Skip to content

gaconkzk/socket.io-client-go

 
 

Repository files navigation

Forked here since I need to make some customization for this to worked on my personal project

golang socket.io is an implementation for the socket.io protocol in Go. There is a lack of specification for the socket.io protocol, so reverse engineering is the easiest way to find out how it works.

This is a work in progress. Many features, such as middleware and binary support, are missing.

golang socket.io is an adapted work from github.com/graarh/golang-socketio.

golang socket.io is forked from github.com/LiferayCloud/archived-gosocketio.


on "connection", "error", and "disconnection"

socket.io has three special events it triggers on the client-side and you should not emit them on your own programs.

Wait for the socket.io connection event before emitting messages or you risk losing them due in an unpredictable fashion (due to concurrency: connection latency, server load, etc.). For the default namespace this is automatically handled on gosocketio.Connect.

However, before emitting a message on a custom namespace, you want to wait for the ready signal, like so:

ctx, cancel := context.WithTimeout(context.Background(), 10 * time.Second)
defer cancel()

select {
	case <-ctx.Done():
		return ctx.Err()
	case <-exampleNamespace.Ready():
		// don't need to do anything
}

if err := exampleNamespace.Emit("fleet", 100); err != nil {
	return err
}

The reason why you probably want to use a select receiving a second channel, such as context.Done() on all non-trivial programs is to avoid program loop, leak memory, or both in case of failure.

The default namespace is automatically ready after establishing the socket.io session. Therefore, *gosocketio.Client doesn't expose a Ready() method.

Connecting to a socket.io server with a custom namespace

You can connect to a namespace and start emitting messages to it with:

c, err := gosocketio.ConnectContext(ctx, u, websocket.NewTransport())

if err != nil {
	return err
}

// ...

exampleNamespace, err := c.Of("example")

If err != nil {
	return err
}

<-exampleNamespace.Ready() // don't do this, use a select like shown above instead!

If err := exampleNamespace.Emit("list", "friends"); err != nil {
	return err
}

Running the example

  1. npm install to install the dependencies for the example server
  2. node server.js
  3. go run example.go

If you need to improve this library you should consider reading full client of original socketio for reference:

About

Go socket.io client forked from https://github.com/graarh/golang-socketio and heavily modified.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Go 86.7%
  • JavaScript 9.2%
  • Shell 2.5%
  • Makefile 1.6%