dongmou5628 2019-06-20 18:53
浏览 161
已采纳

无法连接时停止频道

I have the following code which works ok, the issue is that when the socket.Connect() fails to connect I want to stop the process, I’ve tried with the following code but it’s not working, I.e. if the socket connect fails to connect the program still runs. What I want to happen is that if the connect fails, the process stops and the channe…what am I missing here?

func run (appName string) (err error) {


        done = make(chan bool)
        defer close(done)


        serviceURL, e := GetContext().getServiceURL(appName)

        if e != nil {
            err = errors.New("process failed" + err.Error())
            LogDebug("Exiting %v func[err =%v]", methodName, err)
            return err
        }

        url := "wss://" + serviceURL + route


        socket := gowebsocket.New(url)
        addPass(&socket, user, pass)


        socket.OnConnectError = OnConnectErrorHandler
        socket.OnConnected = OnConnectedHandler
        socket.OnTextMessage = socketTextMessageHandler
        socket.OnDisconnected = OnDisconnectedHandler

        LogDebug("In %v func connecting to URL  %v", methodName, url)
        socket.Connect()

        jsonBytes, e := json.Marshal(payload)
        if e != nil {
            err = errors.New("build process failed" + e.Error())
            LogDebug("Exiting %v func[err =%v]", methodName, err)
            return err
        }

        jsonStr := string(jsonBytes)

        LogDebug("In %v Connecting to payload JSON is  %v", methodName, jsonStr)
        socket.SendText(jsonStr)

        <-done
        LogDebug("Exiting %v func[err =%v]", methodName, err)
        return err

    }


    func OnConnectErrorHandler(err error, socket gowebsocket.Socket) {
        methodName := "OnConnectErrorHandler"
        LogDebug("Starting %v parameters [err = %v , socket = %v]", methodName, err, socket)
        LogInfo("Disconnected from server ")
        done <- true
    }

The process should open one ws connection for process that runs about 60-90 sec (like execute npm install) and get the logs of the process via web socket and when it finish , and of course handle the issue that could happen like network issue or some error running the process

  • 写回答

2条回答 默认 最新

  • doupu0619 2019-06-21 04:18
    关注

    So, @Slabgorb is correct - if you look here (https://github.com/sacOO7/GoWebsocket/blob/master/gowebsocket.go#L87) you will see that the OnConnectErrorHandler is called synchronously during the execution of your call to Connect(). The Connect() function doesn't kick off a separate goroutine to handle the websocket until after the connection is fully established and the OnConnected callback has completed. So when you try to write to the unbuffered channel done, you are blocking the same goroutine that called into the run() function to begin with, and you deadlock yourself, because no goroutine will ever be able to read from the channel to unblock you.

    So you could go with his solution and turn it into a buffered channel, and that will work, but my suggestion would be not to write to a channel for this sort of one-time flag behavior, but use close signaling instead. Define a channel for each condition you want to terminate run(), and in the appropriate websocket handler function, close the channel when that condition happens. At the bottom of run(), you can select on all the channels, and exit when the first one closes. It would look something like this:

    package main
    
    import "errors"
    
    func run(appName string) (err error) {
    
        // first, define one channel per socket-closing-reason (DO NOT defer close these channels.)
        connectErrorChan := make(chan struct{})
        successDoneChan := make(chan struct{})
        surpriseDisconnectChan := make(chan struct{})
    
        // next, wrap calls to your handlers in a closure `https://gobyexample.com/closures`
        // that captures a reference to the channel you care about
        OnConnectErrorHandler := func(err error, socket gowebsocket.Socket) {
            MyOnConnectErrorHandler(connectErrorChan, err, socket)
        }
        OnDisconnectedHandler := func(err error, socket gowebsocket.Socket) {
            MyOnDisconectedHandler(surpriseDisconnectChan, err, socket)
        }
        // ... declare any other handlers that might close the connection here
    
        // Do your setup logic here
        // serviceURL, e := GetContext().getServiceURL(appName)
        // . . .
        // socket := gowebsocket.New(url)
    
        socket.OnConnectError = OnConnectErrorHandler
        socket.OnConnected = OnConnectedHandler
        socket.OnTextMessage = socketTextMessageHandler
        socket.OnDisconnected = OnDisconnectedHandler
    
        // Prepare and send your message here...
        // LogDebug("In %v func connecting to URL  %v", methodName, url)
        // . . .
        // socket.SendText(jsonStr)
    
        // now wait for one of your signalling channels to close.
        select { // this will block until one of the handlers signals an exit
        case <-connectError:
            err = errors.New("never connected  :( ")
        case <-successDone:
            socket.Close()
            LogDebug("mission accomplished! :) ")
        case <-surpriseDisconnect:
            err = errors.New("somebody cut the wires!  :O ")
        }
    
        if err != nil {
            LogDebug(err)
        }
        return err
    }
    
    // *Your* connect error handler will take an extra channel as a parameter
    func MyOnConnectErrorHandler(done chan struct{}, err error, socket gowebsocket.Socket) {
        methodName := "OnConnectErrorHandler"
        LogDebug("Starting %v parameters [err = %v , socket = %v]", methodName, err, socket)
        LogInfo("Disconnected from server ")
        close(done) // signal we are done.
    }
    

    This has a few advantages:

    1) You don't need to guess which callbacks happen in-process and which happen in background goroutines (and you don't have to make all your channels buffered 'just in case')

    2) Selecting on the multiple channels lets you find out why you are exiting and maybe handle cleanup or logging differently.

    Note 1: If you choose to use close signaling, you have to use different channels for each source in order to avoid race conditions that might cause a channel to get closed twice from different goroutines (e.g. a timeout happens just as you get back a response, and both handlers fire; the second handler to close the same channel causes a panic.) This is also why you don't want to defer close all the channel at the top of the function.

    Note 2: Not directly relevant to your question, but -- you don't need to close every channel - once all the handles to it go out of scope, the channel will get garbage collected whether or not it has been closed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启