客户端服务端通信:
?sever:
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"net/http"
)
var upgrader = websocket.Upgrader{ //define upgrade(http-->websocket)
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func ping (c *gin.Context){
ws ,err := upgrader.Upgrade(c.Writer,c.Request,nil) //upgrade
if err != nil{
return
}
defer ws.Close()
for { //most important send receive function always
mt,message ,err := ws.ReadMessage()
fmt.Println(string(message))
if err != nil{
break
}
err = ws.WriteMessage(mt,message)
if err != nil{
break
}
}
}
func main (){
r := gin.Default()
r.GET("/ping",ping)
r.Run(":8383")
}
client:
package main
import (
"github.com/gorilla/websocket"
"log"
)
func main (){
client, _, err := websocket.DefaultDialer.Dial("ws://127.0.0.1:8383/ping",nil)
if err != nil {
log.Fatal("dial: ",err)
}
defer client.Close()
err = client.WriteMessage(websocket.TextMessage,[]byte("hello websoccket"))
if err != nil {
log.Println(err)
}
_,msg,err := client.ReadMessage()
if err != nil {
log.Println("read:",err)
return
}
log.Printf("receive :%s\n",msg)
}
|