• gin+websocket


    gin + "golang.org/x/net/websocket"

    package main
    
    import (
    	"github.com/gin-gonic/gin"
    	"golang.org/x/net/websocket"
    	"log"
    	"time"
    )
    
    func main() {
    	log.SetFlags(log.Lshortfile | log.LstdFlags)
    
    	var router = gin.Default()
    	router.GET("/ws", ginWebsocketHandler(wsConnHandle))
    
    	if err := router.Run(":9898"); err != nil {
    		log.Println(err)
    	}
    }
    
    // websocket.Handler 转 gin HandlerFunc
    func ginWebsocketHandler(wsConnHandle websocket.Handler) gin.HandlerFunc {
    	return func(c *gin.Context) {
    		log.Printf("new ws request: %v", c.Request.RemoteAddr)
    		if c.IsWebsocket() {
    			wsConnHandle.ServeHTTP(c.Writer, c.Request)
    		} else {
    			_, _ = c.Writer.WriteString("===not websocket request===")
    		}
    	}
    }
    
    // websocket连接处理
    func wsConnHandle(conn *websocket.Conn) {
    	for {
    		var msg string
    		if err := websocket.Message.Receive(conn, &msg); err != nil {
    			log.Println(err)
    			return
    		}
    
    		log.Printf("recv: %v", msg)
    
    		data := []byte(time.Now().Format(time.RFC3339))
    		if _, err := conn.Write(data); err != nil {
    			log.Println(err)
    			return
    		}
    	}
    }
    

      

  • 相关阅读:
    性能测试相关概念
    java -json()
    jquery ajax 前前后后,所有的函数并查询链接
    jquery ajax get /post
    jquery ajax load
    三个重要属性
    发送请求
    处理返回结果(XML)
    处理返回结果
    调用对象
  • 原文地址:https://www.cnblogs.com/baigoogledu/p/13225567.html
Copyright © 2020-2023  润新知