websocket golang 客户端服务端搭建实例

websocket golang 客户端服务端搭建实例,第1张

客户端服务端通信:

 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)
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/994518.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存