gobwas / ws

Tiny WebSocket library for Go.
MIT License
6.1k stars 373 forks source link

Client-side example? #179

Closed klauspost closed 1 year ago

klauspost commented 1 year ago

Hi!

Sorry for the probably stupid question, but I don't really see how to do a clientside connection to a remote. I see some proxy examples, but they appear to mostly be forwarding requests.

Background

I am implementing a two-way connection between servers that should eventually be able to mux multiple message types. This seems like a great match, since it allows me to control allocations much better than the alternatives.

There is however no "server" and "client" - either can initiate the connection and I have a mechanism for resolving collisions. Do I simply dial and use the connection from that with no direct actions to upgrade on the client?

A client-side example would be great, since it isn't very obvious to me what I should do.

Thanks for the great package. Looking forward to diving deeper into it.

cristaloleg commented 1 year ago

Hey, thanks for the reminder. I was slow on that last month. Will publish a PR in the next few days. In short:

conn, _, _, err := ws.DefaultDialer.Dial(context.Background(), "ws://127.0.0.1:9000")
if err != nil {
    panic(err)
}

for {
    err := wsutil.WriteClientMessage(conn, ws.OpText, []byte{"my message"})
    if err != nil {
        panic(err)
    }

    time.Sleep(time.Second)

    msg, op, err := wsutil.ReadServerData(conn)
    if err != nil {
        panic(err)
    }
}
klauspost commented 1 year ago

Thanks a bunch. Should be enough to get started.

klauspost commented 1 year ago

If you are still reading, I presume that read/write can be in separate goroutines like net.Conn promises.

cristaloleg commented 1 year ago

For simplicity I left them in 1 loop.

klauspost commented 1 year ago

@cristaloleg Just wondering if the internal Control Frame Handling in for example wsutil.ReadData could interfere with it on the server side, or if it is still safe to try to write messages while data is being read.