Print something while read message from server with websocket

103 views
Skip to first unread message

洪嘉鴻

unread,
Mar 25, 2020, 4:10:19 AM3/25/20
to golang-nuts
Hello everyone:
      The version of the golang which I am using is 1.12.9 with Win10.
      I want to print something while the client is waiting for server.
      The following are the partial code of server and client.

      Server:
      time.Sleep(time.Second * 100)
      ws.Write([]byte("Hello!"))
      
      Client:
      while(!ws.Read(msg)){
      fmt.Println("Please wait because server is busy.")      
      }

      Can anyone suggest how to fix the code?

      Any help is appreciated.
      Thank you very much!
      Max

Jake Montgomery

unread,
Mar 25, 2020, 9:28:37 AM3/25/20
to golang-nuts
You do not provide enough information to give a really good answer. There are a number of ways to achieve this, but they depend on the details. A more complete example would help.

What is the type of `ws`? If it is something on which you can set a read timeout, then one way would be to set a timeout, and loop.

洪嘉鴻

unread,
Mar 25, 2020, 8:56:57 PM3/25/20
to golang-nuts
I'm sorry.
The followings are the complete codes of server and client:

Thank you very much!
      Max

Jake Montgomery於 2020年3月25日星期三 UTC+8下午9時28分37秒寫道:

Jake Montgomery

unread,
Mar 26, 2020, 1:12:07 PM3/26/20
to golang-nuts
Your Client code does not compile. As a courtesy to those trying to help, it is always good to test your code before posting it. A working example, without your "busy" messages would be something like: https://play.golang.org/p/cvgwd8GDobc . The Read() method documentation says "Read implements the io.Reader interface." So I suggest you carefully read the io.Reader documentation, because it requires very specific handling to be done correctly.

Also, I did note that golang.org/x/net/websocket documentation states that: "This package currently lacks some features found in alternative and more actively maintained WebSocket packages." So you may want to consider using one of those.

I have not actually used golang.org/x/net/websocket myself, but there is a SetReadDeadline() function. Because I have not used the package before, there may be some hidden pitfalls that I am missing, but this code seems to do what you want, using SetReadDeadline(): https://play.golang.org/p/ISUR7c_Mtqb

Good luck
Message has been deleted
Message has been deleted

洪嘉鴻

unread,
Mar 27, 2020, 2:52:25 AM3/27/20
to golang-nuts
I'm sorry that I didn't remind that my Client code does not compile.
I've tried your example with SetReadDeadline().
It seems like what I want to do.

Thank you very much!
      Max

Jake Montgomery於 2020年3月27日星期五 UTC+8上午1時12分07秒寫道:
Reply all
Reply to author
Forward
0 new messages