golang vue 使用 websocket 的例子

一. 编写golang服务端

 1.导入必要的websocket包,golang.org/x/net/websocket 或 github.com/golang/net/websocket

 2.编写消息处理函数,主要实现接收客户端发送的消息和向客户端发送消息

 

func Handle(conn *websocket.Conn) {
defer conn.Close()
jsonHandler := websocket.JSON
userInfo := &UserInfo{}
res := &Response{
Code: 1,
Msg: "success",
}
go Push(conn)
for {
err := jsonHandler.Receive(conn, userInfo)
if err != nil {
fmt.Println(err)
break
}
jsonData, _ := json.Marshal(userInfo)
fmt.Println("receive data:", string(jsonData[:]))
err = jsonHandler.Send(conn, res)
if err != nil {
fmt.Println(err)
break
}
}
}

 3.绑定地址及端口


package main

import (
"fmt"
"golang.org/x/net/websocket"
"net/http"
"w3liu.com/websocket/handler"
)

func main() {
http.Handle("/ws", websocket.Handler(handler.Handle))
err := http.ListenAndServe(":88", nil)
if err != nil {
fmt.Println(err)
}
}

 

二、编写VUE客户端

  

< template >
< div >
{{ msg}}
</ div >
</ template >
< script >
export default {
data () {
return {
websock: null,
msg: ''
}
},
methods: {
init : function () {
const wsurl = 'ws://127.0.0.1:88/ws'
this. websock = new WebSocket( wsurl)
this. websock. onmessage = this. onmessage
this. websock. onopen = this. onopen
this. websock. onerror = this. onerror
this. websock. onclose = this. onclose
},
onopen : function () {
this. send( '{"userid":1, "name":"zhang san", "age":"30"}')
},
send : function ( data) {
for ( var i = 0; i < 10; i++) {
this. websock. send( data)
}
},
onclose : function ( e) {
console. log( 'ws close', e)
},
onmessage : function ( e) {
let _this = this
console. log( e. data)
_this. msg = e. data
},
onerror : function () {
console. log( 'ws error')
this. init()
}
},
mounted : function () {
this. init()
},
watch: {
}
}
</ script >

 

 完整源码访问:https://github.com/w3liu/websocket

 

转载于:https://www.cnblogs.com/w3liu/p/10590779.html

要在Golang使用WebSocket,你可以使用`github.com/gorilla/websocket`包。首先,你需要安装该包: ``` go get github.com/gorilla/websocket ``` 然后,你可以使用以下代码示例创建WebSocket服务器和客户端: ```go // 服务器端 package main import ( "fmt" "log" "net/http" "github.com/gorilla/websocket" ) // 处理WebSocket连接 func handleWebSocket(w http.ResponseWriter, r *http.Request) { // 升级HTTP连接为WebSocket协议 conn, err := websocket.Upgrade(w, r, nil, 1024, 1024) if err != nil { log.Println(err) return } defer conn.Close() // 在这里处理WebSocket消息 for { // 读取客户端发送的消息 _, msg, err := conn.ReadMessage() if err != nil { log.Println(err) break } fmt.Println(string(msg)) // 发送消息给客户端 if err := conn.WriteMessage(websocket.TextMessage, []byte("Hello from server")); err != nil { log.Println(err) break } } } func main() { http.HandleFunc("/", handleWebSocket) log.Fatal(http.ListenAndServe(":8080", nil)) } // 客户端 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: "/"} 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 } fmt.Printf("received: %s\n", 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 } } } ``` 这是一个简单的示例,服务器接收客户端的消息并将其打印出来,然后向客户端发送"Hello from server"的消息。客户端定期向服务器发送当前时间。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值