我需要使用go lang连接到现有的websocket服务器

时间:2015-09-23 17:21:24

标签: go websocket gorilla

我的本​​地主机- (void)presentNewUserInterface { UIViewController* rootController = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"newuser"]; UINavigationController* navigation = [[UINavigationController alloc] initWithRootViewController:rootController]; self.window.rootViewController = navigation; }

上运行了一个websocket

我需要go lang代码,可以创建一个websocket客户端并连接到这个服务器。

我的Google-Fu技能未能教会我一个简单的方法。

谢谢。

2 个答案:

答案 0 :(得分:13)

没关系我在网上发现了一些帮助代码。现在我的代码看起来像这样,以防其他人需要这个:

package main

import (
        "net/http"
        "text/template"
        "code.google.com/p/go.net/websocket"
        "fmt"
        "os"
        "time"
)


const address string = "localhost:9999"

func main() {

    initWebsocketClient()
}


func initWebsocketClient() {
    fmt.Println("Starting Client")
    ws, err := websocket.Dial(fmt.Sprintf("ws://%s/ws", address), "", fmt.Sprintf("http://%s/", address))
    if err != nil {
        fmt.Printf("Dial failed: %s\n", err.Error())
        os.Exit(1)
    }
    incomingMessages := make(chan string)
    go readClientMessages(ws, incomingMessages)
    i := 0
    for {
        select {
        case <-time.After(time.Duration(2e9)):
            i++
            response := new(Message)
            response.RequestID = i
            response.Command = "Eject the hot dog."
            err = websocket.JSON.Send(ws, response)
            if err != nil {
                fmt.Printf("Send failed: %s\n", err.Error())
                os.Exit(1)
            }
        case message := <-incomingMessages:
            fmt.Println(`Message Received:`,message)


        }
    }
}

func readClientMessages(ws *websocket.Conn, incomingMessages chan string) {
    for {
        var message string
        // err := websocket.JSON.Receive(ws, &message)
        err := websocket.Message.Receive(ws, &message)
        if err != nil {
            fmt.Printf("Error::: %s\n", err.Error())
            return
        }
        incomingMessages <- message
    }
}

正如recoba在评论中所建议的那样,对于寻求更好解决方案的人来说,有一个新的gorilla example here

答案 1 :(得分:5)

查看这个基于事件的客户端,非常简单:https://github.com/rgamba/evtwebsocket

示例:

package main

import (
    "fmt"

    "github.com/rgamba/evtwebsocket"

    "golang.org/x/net/websocket"
)

func main() {
  c := evtwebsocket.Conn{
    OnConnected: func(w *websocket.Conn) {
        fmt.Println("Connected")
    },
    OnMessage: func(msg []byte) {
        fmt.Printf("Received message: %s\n", msg)
    },
    OnError: func(err error) {
        fmt.Printf("** ERROR **\n%s\n", err.Error())
    },
  }
  // Connect
  c.Dial("ws://echo.websocket.org")
  c.Send([]byte("TEST"), nil)
}