echo

package main

import(
    "flag"
    "net/http"
    "github.com/gorilla/websocket"
    "fmt"
)
var addr=flag.String("addr","localhost:8080","http serve addredd")

var upgrader=websocket.Upgrader{
    ReadBufferSize:1024,
    WriteBufferSize:1024,
}
// 

func main(){
    flag.Parse()
    http.HandleFunc("/",index)
    http.HandleFunc("/ws",ws)
    http.ListenAndServe(*addr,nil)
}
func index(w http.ResponseWriter,r *http.Request){
    http.ServeFile(w,r,"index.html")
}
func ws(w http.ResponseWriter,r *http.Request){
    conn,err:=upgrader.Upgrade(w,r,nil)
    // conn类型表示websocket连接,服务器应该先调用升级方法,把http请求升级为websocket连接


    if err!=nil{
        fmt.Println("失败1")
        return 
    }
    defer conn.Close()
    for{
        messageType,msg,err:=conn.ReadMessage()
        // 接收消息
        // msg:字节
        // messageType:text或者文件类型
        
        fmt.Println("收到消息",string(msg),messageType)
        if err!=nil{
            fmt.Println("失败2")
            break
        }
        err=conn.WriteMessage(messageType,msg)
        // 发送消息
        if err!=nil{
            fmt.Println("失败3")
            break;
        }
    }
}

你可能感兴趣的:(echo)