antoniodipinto / ikisocket

🧬 WebSocket wrapper with event management for Fiber https://github.com/gofiber/fiber. Based on Fiber WebSocket and inspired by Socket.io
MIT License
123 stars 21 forks source link

(Question) custom events #17

Closed axk2 closed 2 years ago

axk2 commented 3 years ago

Can i send custom events from websocket (frontend)? Or should i use socket.io?

may be is a noob question, but if i do

socket.send("string") In my frontend, how the backend will know what specific string event is?

Or should i use a json, (as a string)?

If it's a json, what property indicates the event and the message?

Thanks, looks like a great library

antoniodipinto commented 3 years ago

Hi, you can send a custom event whenever you want from the front-end. In this example (https://github.com/antoniodipinto/ikisocket/blob/master/examples/custom_event_example/main.go) you can see that the event name should be inside the payload that you're sending. If you're sending a JSON, you can check the event key in the json.

Nothing it's hardcoded inside ikisocket, to not force the developer to use a specific payload.

If you check line 55 of the https://github.com/antoniodipinto/ikisocket/blob/master/examples/custom_event_example/main.go#L55 you can understand how this works.

You decode the event name, and then you fire the event (line 77)

I hope this help

axk2 commented 3 years ago

if i do in my frontend:

let ws = new WebSocket("ws://127.0.0.1:8010/ws/334")

ws.onopen = (socket: any) => {
    console.log('a user connected')

    const message = {
        data: "hi there",
        from: "me",
        event: "my_event",
        to: ""
    }

    ws.send(JSON.stringify(message))
}

in my backend always will trigger

ikisocket.On(ikisocket.EventMessage, func(ep *ikisocket.EventPayload) {
    // this function will run in every ws.send
})

it is possible to do this?

ikisocket.On("my_custom_event", func(ep *ikisocket.EventPayload) {
    // i've tried to connect with socket.io client but i failed
})

https://github.com/websockets/ws/issues/618

since ws in frontend can't send custom events, how could i trigger "my_custom_event" in my backend? from the frontend?

or may be i should

ikisocket.On(ikisocket.EventMessage, func(ep *ikisocket.EventPayload) {
    message := MessageObject{}

    // Unmarshal the json message
    // {
        //  "from": "<user-id>",
        //  "to": "<recipient-user-id>",
        //  "event": "CUSTOM_EVENT",
        //  "data": "hello"
    // }

    err := json.Unmarshal(ep.Data, &message)
    if err != nil {
        fmt.Println(err)
        return
    }

    if message.Event == "EVENT_ONE" {
        // run specific logic
    }

    if message.Event == "EVENT_TWO" {
        // run another logic
    }
})
antoniodipinto commented 3 years ago

You are missing one piece, you're not firing the event when you receive the message. If you check the example, the event should be fired and just after that, the .On callback will be fired

axk2 commented 3 years ago

If i Understand

kws.Fire("custom_event", []byte("my information"))

will fire an event But, In my Backend

i would like to Fire a custom event to my frontend from the backend

ws.addEventListener('frontend_event', (data) => {
     console.log(data.data)
})

it is possible to do that? with kws object or another object? i was looking in the source code, but i didn't saw a function

antoniodipinto commented 3 years ago

What you can do here is something like that

ws.addEventListener('frontend_event', (data) => {
    const message = {
        data: data,
        from: "me",
        event: "my_event",
        to: ""
    }

    ws.send(JSON.stringify(message))
})

// Custom event handling supported
ikisocket.On("my_event", func(ep *ikisocket.EventPayload) {
    // --->

    // DO YOUR BUSINESS HERE WITH THE DATA THAT YOU'RE SENDING IN THE PAYLOAD

    // --->
})

ikisocket.On(ikisocket.EventMessage, func(ep *ikisocket.EventPayload) {
    message := MessageObject{}

    // Unmarshal the json message
    // {
        //  "from": "<user-id>",
        //  "to": "<recipient-user-id>",
        //  "event": "CUSTOM_EVENT",
        //  "data": "hello"
    // }

    err := json.Unmarshal(ep.Data, &message)
    if err != nil {
        fmt.Println(err)
        return
    }

    // Fire custom event based on some
    // business logic

     // The EVENT NAME it retrieved from the JSON that you're sending
     if message.Event != "" {
          ep.Kws.Fire(message.Event, []byte(message.Data))
     }
})

Remember that this:

// Unmarshal the json message
    // {
        //  "from": "<user-id>",
        //  "to": "<recipient-user-id>",
        //  "event": "CUSTOM_EVENT",
        //  "data": "hello"
    // }

It's just an example, you can define your structure as you wish, nothing is hardcoded, there is not need to preserve the structure in the example

axk2 commented 3 years ago

sorry, my english is very bad, but actually i want know how to trigger "frontend event", it is possible? because my frontend in this moment it's only listening "onmessage", and i had a switch satement to separate some logic.

antoniodipinto commented 3 years ago

I'm sorry but I don't think I understand anymore what you really need. Can you please try to explain what you're trying to achieve?

axk2 commented 3 years ago

Listen ws events in frontend

Js code

ws.addEventListener('frontend_event', (data) => {
     console.log(data.data)
})

Because without events in my frontend, i will only be able to get messages on

ws.onmessage

It is possible to do that?

I was confused because i use to belive that "fire" could work in both sides, frontend and backend just like socket io:

socket.emit("hello", "world") 

Like this example https://socket.io/docs/v3/emitting-events/