package main

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

func main() {
	http.Handle("/", websocket.Handler(Echo)) //这里校验请求头的Origin字段
	if err := http.ListenAndServe("127.0.0.1:9999", nil); err != nil {
		log.Fatal("ListenAndServer: ", err)
	}
}

func Echo(ws *websocket.Conn) {
	var err error
	for {
		var reply string
		err = websocket.Message.Receive(ws, &reply)
		if err != nil {
			fmt.Println("Can't receive data...")
			break
		}
		fmt.Println("Receive back from client:" + reply)
		msg := "Receive: " + "接受到客户端的消息，ok"
		fmt.Println("Sending to client: " + msg)

		err = websocket.Message.Send(ws, msg)
		if err != nil {
			fmt.Println("发送消息失败")
			break
		}

	}

}
