websocketgolang客户端服务端搭建实例客户端服务端通信:
ver:
package main
嗅觉失灵的原因import (
"fmt"
"/gin-gonic/gin"
"/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.Clo()
for { //most important nd 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 mainip地址配置
import (
"/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.Clo()
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)
}