我需要使用Go语言连接到一个已存在的WebSocket服务器。

huangapple go评论99阅读模式
英文:

I need to connect to an existing websocket server using go lang

问题

以下是一个可以创建 WebSocket 客户端并连接到指定服务器的 Go 语言代码:

package main

import (
	"fmt"
	"log"
	"net/url"
	"os"
	"os/signal"
	"time"

	"github.com/gorilla/websocket"
)

func main() {
	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt)

	u := url.URL{Scheme: "ws", Host: "localhost:8080", Path: "/ws"}
	log.Printf("connecting to %s", u.String())

	c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
	if err != nil {
		log.Fatal("dial:", err)
	}
	defer c.Close()

	done := make(chan struct{})

	go func() {
		defer close(done)
		for {
			_, message, err := c.ReadMessage()
			if err != nil {
				log.Println("read:", err)
				return
			}
			log.Printf("received: %s", message)
		}
	}()

	ticker := time.NewTicker(time.Second)
	defer ticker.Stop()

	for {
		select {
		case <-done:
			return
		case t := <-ticker.C:
			err := c.WriteMessage(websocket.TextMessage, []byte(t.String()))
			if err != nil {
				log.Println("write:", err)
				return
			}
		case <-interrupt:
			log.Println("interrupt")

			err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
			if err != nil {
				log.Println("write close:", err)
				return
			}
			select {
			case <-done:
			case <-time.After(time.Second):
			}
			return
		}
	}
}

请注意,上述代码使用了 gorilla/websocket 包来处理 WebSocket 连接。你可以使用 go get 命令安装该包:

go get github.com/gorilla/websocket

希望这可以帮助到你!如果你有任何其他问题,请随时问我。

英文:

Theres a websocket running in my localhost on ws://localhost:8080/ws

I need go lang code that can create a websocket client and connect to this server.

My Google-Fu skills failed to teach me a simple way to do this.

Thank you.

答案1

得分: 21

不好意思,我只能提供中文翻译。以下是您要翻译的内容:

不用担心,我在网上找到了一些帮助代码。现在我的代码如下,以防其他人需要:

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.Message.Receive(ws, &message)
        if err != nil {
            fmt.Printf("Error: %s\n", err.Error())
            return
        }
        incomingMessages <- message
    }
}

另外,正如recoba在评论中建议的那样,对于那些寻找更好解决方案的人,这里有一个新的gorilla示例

英文:

Nevermind I found some helping code online. Now my code looks like this in case someone else needs this:

package main
import (
&quot;net/http&quot;
&quot;text/template&quot;
&quot;code.google.com/p/go.net/websocket&quot;
&quot;fmt&quot;
&quot;os&quot;
&quot;time&quot;
)
const address string = &quot;localhost:9999&quot;
func main() {
initWebsocketClient()
}
func initWebsocketClient() {
fmt.Println(&quot;Starting Client&quot;)
ws, err := websocket.Dial(fmt.Sprintf(&quot;ws://%s/ws&quot;, address), &quot;&quot;, fmt.Sprintf(&quot;http://%s/&quot;, address))
if err != nil {
fmt.Printf(&quot;Dial failed: %s\n&quot;, err.Error())
os.Exit(1)
}
incomingMessages := make(chan string)
go readClientMessages(ws, incomingMessages)
i := 0
for {
select {
case &lt;-time.After(time.Duration(2e9)):
i++
response := new(Message)
response.RequestID = i
response.Command = &quot;Eject the hot dog.&quot;
err = websocket.JSON.Send(ws, response)
if err != nil {
fmt.Printf(&quot;Send failed: %s\n&quot;, err.Error())
os.Exit(1)
}
case message := &lt;-incomingMessages:
fmt.Println(`Message Received:`,message)
}
}
}
func readClientMessages(ws *websocket.Conn, incomingMessages chan string) {
for {
var message string
// err := websocket.JSON.Receive(ws, &amp;message)
err := websocket.Message.Receive(ws, &amp;message)
if err != nil {
fmt.Printf(&quot;Error::: %s\n&quot;, err.Error())
return
}
incomingMessages &lt;- message
}
}

Also as recoba suggested in the comment, there has been a new gorilla example here for the ones looking for a better solution.

答案2

得分: 6

请注意,我是一个文本模型,无法直接访问互联网或打开链接。但是,我可以为您提供代码的翻译。以下是您提供的代码的翻译:

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("已连接")
		},
		OnMessage: func(msg []byte) {
			fmt.Printf("收到消息:%s\n", msg)
		},
		OnError: func(err error) {
			fmt.Printf("** 错误 **\n%s\n", err.Error())
		},
	}
	// 连接
	c.Dial("ws://echo.websocket.org")
	c.Send([]byte("测试"), nil)
}

这是一个使用evtwebsocket库的事件驱动客户端的示例代码。它通过WebSocket连接到"ws://echo.websocket.org",并在连接成功后打印"已连接",接收到消息时打印消息内容,发生错误时打印错误信息。在示例中,它发送了一个"测试"的消息。

英文:

Check out this event-based client, super easy: https://github.com/rgamba/evtwebsocket

Example:

package main
import (
&quot;fmt&quot;
&quot;github.com/rgamba/evtwebsocket&quot;
&quot;golang.org/x/net/websocket&quot;
)
func main() {
c := evtwebsocket.Conn{
OnConnected: func(w *websocket.Conn) {
fmt.Println(&quot;Connected&quot;)
},
OnMessage: func(msg []byte) {
fmt.Printf(&quot;Received message: %s\n&quot;, msg)
},
OnError: func(err error) {
fmt.Printf(&quot;** ERROR **\n%s\n&quot;, err.Error())
},
}
// Connect
c.Dial(&quot;ws://echo.websocket.org&quot;)
c.Send([]byte(&quot;TEST&quot;), nil)
}

huangapple
  • 本文由 发表于 2015年9月24日 01:21:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/32745716.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定