sooon
sooon

Reputation: 4888

Websocket dialer maintain the websocket connection

I am testing with Go websocket dialer to connect with my own websocket server. This is the dialer code:

package main

import (
    "log"
    "github.com/gorilla/websocket"
)

var (
    ws  *websocket.Conn
)

func main() {

    //add self as sender client
    u := "ws://localhost:5005/ws"
    log.Printf("Connecting to %s", u)
    ws, res, err := websocket.DefaultDialer.Dial(u, nil)
    if err != nil {
        log.Println("[DIAL]", err)
    }
    log.Println(ws)
    log.Println(res)
}

and my server code:

    package main
    
    import (
        "fmt"
        "io/ioutil"
        "log"
        "net/http"
        "pubsubserver/pubsub"
    
        "github.com/gorilla/websocket"
        uuid "github.com/satori/go.uuid"
        "github.com/valyala/fasthttp"
    )
    
    var upgrader = websocket.Upgrader{
        ReadBufferSize:  1024,
        WriteBufferSize: 1024,
    }
    
    
    func websocketHandler(w http.ResponseWriter, r *http.Request) {
        upgrader.CheckOrigin = func(r *http.Request) bool { return true }
        conn, err := upgrader.Upgrade(w, r, nil)
        if err != nil {
            log.Println(err)
            return
        }
        
        //... some process to add client
    
        fmt.Println("new client connected.")
    
        for {
           //... some process to handle client message
            }
            ps.HandleReceivedMessage(client, messageType, p)
        }
    }
    
    func main() {
        http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            http.ServeFile(w, r, "static")
        })
        http.HandleFunc("/ws", websocketHandler)
    
        err := http.ListenAndServe(":5005", nil)
        if err != nil {
            log.Println("http server err: ",err)
    
            return
        }
}

I run my server, the run the dialer.go. my server with return some message:

new client connected.

2020/12/03 11:01:19 connection err: read tcp[::1]:5005->[::1]:55227: read: connection reset by peer

by the log message, am I right to assume the connection is successful, but the dialer close connection immediately after success connected?

How can I get the dialer to persist the connection after connected to the websocket server?

Upvotes: 0

Views: 2562

Answers (2)

user26420870
user26420870

Reputation: 11

I will suggest to use this library which is based on gorilla websocket and provides a toolset to handle websockets.

https://github.com/padaliyajay/socketconsumer

Upvotes: 1

Neeymor
Neeymor

Reputation: 1

To prevent the application form exiting, add the following line of code to the end of the function main():

 select {} // block forever.

This will keep the connection open, but will not do anything useful with it.

Upvotes: 0

Related Questions