wesocket

websocket包:https://github.com/gorilla/websocket

先从普通http开始

package main

import "net/http"

func main() {
    http.HandleFunc("/ws",handleFunc)

    http.ListenAndServe(":9090",nil)
}

func handleFunc(w http.ResponseWriter, req *http.Request) {
    w.Write([]byte("hello world"))
}

访问: http://localhost:9090 验证

 

升级 websocket 

package main

import (
    "fmt"
    "log"
    "net/http"
    "time"

    "github.com/gorilla/websocket"
)

func main() {
    http.HandleFunc("/ws",handleFunc)

    http.ListenAndServe(":9090",nil)
}

func handleFunc(w http.ResponseWriter, req *http.Request) {
    // websocket 一些设置
    u := websocket.Upgrader{
        CheckOrigin: func(r *http.Request) bool {
            return true // 直接允许非同源
        },
    }

    // 开始升级 ws
    c,err := u.Upgrade(w, req, nil)
    if err != nil {
        log.Fatalf("升级ws失败: %v", err)
    }
    defer c.Close()

    // 接收客户端发的数据
    go func() {
        for {
            m := make(map[string]string)
            err := c.ReadJSON(&m)
            if err != nil {
                fmt.Printf("读取客户端消息失败: %v\n", err)
                return
            }
            fmt.Println(m)
        }
    }()

    // 给客户端返回数据
    for{
        err := c.WriteJSON(map[string]string{
            "data": "haha",
            "code": "1",
        })
        if err != nil {
            fmt.Printf("发送给客户端失败: %v\n", err)
            return
        }
        time.Sleep(3 * time.Second)
    }

    //w.Write([]byte("hello world"))
}

直接用postman验证

 

posted @ 2022-05-11 23:23  JaydenQiu  阅读(27)  评论(0)    收藏  举报