go实现websocket案例

go实现websocket案例_第1张图片

package main

import (
	"bytes"
	"fmt"
	"log"
	"net/http"
	"unsafe"

	"golang.org/x/net/websocket"
)

func ByteToString(p *byte) string {
     
	bufs := bytes.NewBufferString("")
	for ps := p; *ps != byte(0); ps = (*byte)(unsafe.Pointer(1 + (uintptr)(unsafe.Pointer(ps)))) {
     
		bufs.WriteByte(*ps)
	}
	return bufs.String()
}

func main() {
     
	fmt.Println("websocket地址: ws://127.0.0.1:8080/runtime")
	http.Handle("/runtime", websocket.Handler(echo))
	if err := http.ListenAndServe(":8080", nil); err != nil {
     
		log.Fatal(err)
	}
}

//测试地址: http://coolaf.com/tool/chattest  首字母大写是公有的  Echo,首字母小写是私有的 echo
func echo(w *websocket.Conn) {
     
	var error error
	for {
     
		//只支持string类型
		var reply string
		if error = websocket.Message.Receive(w, &reply); error != nil {
     
			log.Println("websocket出现异常", error)
			break
		}
		fmt.Println("收到客户端消息:" + reply)
		msg := reply + ", 我是服务端"
		fmt.Println("发送客户端消息:" + msg)
		if error = websocket.Message.Send(w, msg); error != nil {
     
			log.Println("websocket出现异常", error)
			break
		}
	}
}

你可能感兴趣的:(GO开发,go实现websocket,golang,websocket,go语言实现websocket,go)