golang websocket 示例

websocket 包:

golang.org/x/net/websocket

通过js websocket连接未出现跨域问题。

package main

import (
	"fmt"
	"golang.org/x/net/websocket"
	"net/http"
);

func echoHandler(ws *websocket.Conn) {


	defer func() {
		if r := recover(); r!=nil{
			fmt.Println(r)
		}
	}()

	msg := make([]byte,512)

	for{

		strLen,err := ws.Read(msg)

		fmt.Println(string(msg[:strLen-1]))
		fmt.Println(strLen)

		if err !=nil {
			panic(err)
		}

	}

}

func main(){

	mux := http.NewServeMux()
	mux.Handle("/ws",websocket.Handler(echoHandler))

	server := &http.Server{
		Addr : ":9990",
		Handler: mux,
		IdleTimeout: 9999,
	}

	defer func(){
		if r:= recover(); r!= nil {
			fmt.Println(r)
			_ = server.Close()
		}
	}()

	if err := server.ListenAndServe();err != nil {
		panic(err)
	}

}

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页