GithubHelp home page GithubHelp logo

sacoo7 / socketcluster-client-go Goto Github PK

View Code? Open in Web Editor NEW
55.0 5.0 20.0 53 KB

GO client for socketcluster

Home Page: https://socketcluster.io/

License: Apache License 2.0

Go 98.24% Shell 1.76%
golang gorilla websocket socketcluster-client

socketcluster-client-go's Introduction

socketcluster-client-go

Refer examples for more details :

Overview

This client provides following functionality

  • Easy to setup and use
  • Support for emitting and listening to remote events
  • Pub/sub
  • Authentication (JWT)
  • Can be used for testing of all server side functions

To install use

    go get github.com/sacOO7/socketcluster-client-go/scclient

Description

Create instance of scclient by passing url of socketcluster-server end-point

    //Create a client instance
    client := scclient.New("ws://192.168.100.11:8000/socketcluster/");
    

Important Note : Default url to socketcluster end-point is always ws://somedomainname.com/socketcluster/.

Registering basic listeners

Different functions are given as an argument to register listeners

        package main
        
        import (
        	"github.com/sacOO7/socketcluster-client-go/scclient"
        	"text/scanner"
        	"os"
        	"fmt"
        )
        
        func onConnect(client scclient.Client) {
            fmt.Println("Connected to server")
        }
        
        func onDisconnect(client scclient.Client, err error) {
            fmt.Printf("Error: %s\n", err.Error())
        }
        
        func onConnectError(client scclient.Client, err error) {
            fmt.Printf("Error: %s\n", err.Error())
        }
        
        func onSetAuthentication(client scclient.Client, token string) {
            fmt.Println("Auth token received :", token)
        
        }
        
        func onAuthentication(client scclient.Client, isAuthenticated bool) {
            fmt.Println("Client authenticated :", isAuthenticated)
            go startCode(client)
        }  
            
        func main() {
        	var reader scanner.Scanner
        	client := scclient.New("ws://192.168.100.11:8000/socketcluster/");
        	client.SetBasicListener(onConnect, onConnectError, onDisconnect)
        	client.SetAuthenticationListener(onSetAuthentication, onAuthentication)
        	go client.Connect()
        
        	fmt.Println("Enter any key to terminate the program")
        	reader.Init(os.Stdin)
        	reader.Next()
        	// os.Exit(0)
        }
        
        func startCode(client scclient.Client) {
        	// start writing your code from here
        	// All emit, receive and publish events
        }
        

Connecting to server

  • For connecting to server:
    //This will send websocket handshake request to socketcluster-server
    client.Connect()

Emitting and listening to events

Event emitter

  • eventname is name of event and message can be String, boolean, int or structure
    client.Emit(eventname,message);
        
    //  client.Emit("chat","This is a sample message")
  • To send event with acknowledgement
	client.EmitAck("chat","This is a sample message", func(eventName string, error interface{}, data interface{}) {
		if error == nil {
			fmt.Println("Got ack for emit event with data ", data, " and error ", error)
		}
	})
	

Event Listener

  • For listening to events :

The object received can be String, Boolean, Long or GO structure.

    // Receiver code without sending acknowledgement back
    client.On("chat", func(eventName string, data interface{}) {
		fmt.Println("Got data ", data, " for event ", eventName)
	})
    
  • To send acknowledgement back to server
    // Receiver code with ack
	client.OnAck("chat", func(eventName string, data interface{}, ack func(error interface{}, data interface{})) {
		fmt.Println("Got data ", data, " for event ", eventName)
		fmt.Println("Sending back ack for the event")
		ack("This is error", "This is data")
	}) 
        

Implementing Pub-Sub via channels

Creating channel

  • For creating and subscribing to channels:
    // without acknowledgement
    client.Subscribe("mychannel")
    
    //with acknowledgement
    client.SubscribeAck("mychannel", func(channelName string, error interface{}, data interface{}) {
        if error == nil {
            fmt.Println("Subscribed to channel ", channelName, "successfully")
        }
    })

Publishing event on channel

  • For publishing event :
       // without acknowledgement
       client.Publish("mychannel", "This is a data to be published")

       
       // with acknowledgement
       client.PublishAck("mychannel", "This is a data to be published", func(channelName string, error interface{}, data interface{}) {
       		if error == nil {
       			fmt.Println("Data published successfully to channel ", channelName)
       		}
       	})

Listening to channel

  • For listening to channel event :
        client.OnChannel("mychannel", func(channelName string, data interface{}) {
        		fmt.Println("Got data ", data, " for channel ", channelName)
        })
    

Un-subscribing to channel

         // without acknowledgement
        client.Unsubscribe("mychannel")
         
         // with acknowledgement
        client.UnsubscribeAck("mychannel", func(channelName string, error interface{}, data interface{}) {
            if error == nil {
                fmt.Println("Unsubscribed to channel ", channelName, "successfully")
            }
        })

Closing the connection with server

    client.Disconnect()

Setting request headers

	client.RequestHeader.Set("Accept-Encoding","gzip, deflate, sdch")
	client.RequestHeader.Set("Accept-Language","en-US,en;q=0.8")
	client.RequestHeader.Set("Pragma","no-cache")
	client.RequestHeader.Set("User-Agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36")
	

Setting proxy server

  • It can be set using connectionOptions by providing url to proxy server
    client.ConnectionOptions = gowebsocket.ConnectionOptions {
       Proxy: gowebsocket.BuildProxy("http://example.com"),
    }

Setting data compression, ssl verification and subprotocols

  • It can be set using connectionOptions inside socket
    client.ConnectionOptions = gowebsocket.ConnectionOptions {
        UseSSL:true,
        UseCompression:true,
        Subprotocols: [] string{"chat","superchat"},
    }
  • ConnectionOptions needs to be applied before connecting to server

socketcluster-client-go's People

Contributors

sacoo7 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

socketcluster-client-go's Issues

main.go does not work

./main.go:39:8: client.EnableLogging undefined (type scclient.Client has no field or method EnableLogging)

error handling for events

hi,
it would be best practice to have error handling in callbacks that handle exception and return the error back to the connector, especially when its not run via go routine.

onConnect, onDisconnect, onConnectError, onAuthentication, onSetAuthentication

thank you

panic: interface conversion: interface {} is nil, not map[string]interface {}

This happens a few seconds after successfully connecting to the server when I run the code in the README. No message is being published and there's nothing but a fmt.Println in my startCode function.

panic: interface conversion: interface {} is nil, not map[string]interface {}

goroutine 37 [running]:
github.com/sacOO7/socketcluster-client-go/scclient/parser.GetMessageDetails(0x0, 0x0, 0x0, 0x6d7d40, 0xc000058ef0, 0x7cc220, 0xc00000e480, 0x9870b4, 0x9870b4, 0xf4c)
	/go/pkg/mod/github.com/sac!o!o7/[email protected]/scclient/parser/parser.go:28 +0x40e
github.com/sacOO7/socketcluster-client-go/scclient.(*Client).registerCallbacks.func3(0x0, 0x0, 0xc0001ac000, 0xc000106080, 0x76b0e9, 0x26, 0x100, 0x0, 0x0, 0x0, ...)
	/go/pkg/mod/github.com/sac!o!o7/[email protected]/scclient/client.go:65 +0x188
github.com/sacOO7/gowebsocket.(*Socket).Connect.func4(0xc000108020)
	/go/pkg/mod/github.com/sac!o!o7/[email protected]/gowebsocket.go:154 +0x264
created by github.com/sacOO7/gowebsocket.(*Socket).Connect
	/go/pkg/mod/github.com/sac!o!o7/[email protected]/gowebsocket.go:133 +0x50c

Is this client maintained/expected to work with the latest socketcluster server release?

Recieving json bigger 512 symbols

Not working with received JSON bigger than 512 symbols.
In function utils.DeserializeData, json.Unmarshal throws error - unexpected end of JSON input - and return nil. That happened because the resulting json is not complete and the second part comes with the next message.

Library does not work on ARM6

I just tested the library on a Raspberry Pi (ARM6), however, it crashes with the following message:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x120b8]

goroutine 6 [running]:
runtime/internal/atomic.goXadd64(0x1462b4c, 0x1, 0x0, 0x1414300, 0xdd3e8)
	/opt/go/src/runtime/internal/atomic/atomic_arm.go:96 +0x1c
github.com/sacOO7/socketcluster-client-go/scclient/utils.(*AtomicCounter).IncrementAndGet(0x1462b4c, 0x6b980, 0x1464120)
	/home/pi/go/pkg/mod/github.com/sac!o!o7/[email protected]/scclient/utils/counter.go:12 +0x30
github.com/sacOO7/socketcluster-client-go/scclient.(*Client).sendHandshake(0x1462b40)
	/home/pi/go/pkg/mod/github.com/sac!o!o7/[email protected]/scclient/client.go:116 +0x24
github.com/sacOO7/socketcluster-client-go/scclient.(*Client).registerCallbacks.func1(0x14dc000, 0x1448340, 0x14180c0, 0x25, 0x100, 0x0, 0x0, 0x0, 0x0, 0x1446b60, ...)
	/home/pi/go/pkg/mod/github.com/sac!o!o7/[email protected]/scclient/client.go:44 +0x24
github.com/sacOO7/gowebsocket.(*Socket).Connect(0x1462b54)
	/home/pi/go/pkg/mod/github.com/sac!o!o7/[email protected]/gowebsocket.go:96 +0x390
github.com/sacOO7/socketcluster-client-go/scclient.(*Client).Connect(0x1462b40)
	/home/pi/go/pkg/mod/github.com/sac!o!o7/[email protected]/scclient/client.go:112 +0xcc

After digging in, I found a reasonable explanation for that problem, memory alignment.

I patched the code, which now works on ARM6, see my PR:

#11

Would be great to get that fix in, and v1.0.1 is released.

Getting data before deserialization

Hello - would like to ask what you think about the following:

When registering a callback to receive messages, the library code will by default call utils.DeserializeDataFromString on the message and pass a map[string]interface{} to the callback.

If the client code wants to unmarshall the message directly to a struct it has serialize then deserialize again or do an awful lot of copying and casting. Do you think it makes sense to pass back bytes instead?

Manual disconnect, Proxy support

Adding manual disconnect facility and proxy to socketcluster client. I think it is really necessary to have this in all clients.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.