英文:
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 (
"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
}
}
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 (
"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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论