golang编写一个websocket服务端代码
代码语言:golang
所属分类:高性能
代码描述:golang编写一个websocket服务端代码
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
package main import( "net" "log" "strings" "crypto/sha1" "io" "encoding/base64" "errors" ) func main() { ln, err := net.Listen("tcp",":8000") if err != nil { log.Panic(err) } for { conn, err := ln.Accept() if err != nil { log.Println("Accept err:", err) } for { handleConnection(conn) } } } func handleConnection(conn net.Conn) { content := make([]byte, 1024) _, err := conn.Read(content) log.Println(string(content)) if err != nil { log.Println(err) } isHttp := false // 先暂时这么判断 if string(content[0:3]) == "GET" { isHttp = true; } log.Println("isHttp:", isHttp) if isHttp { headers := parseHandshake(string(content)) log.Println("headers", headers) secWebsocketKey := headers["Sec-WebSocket-Key"] // NOTE:这里省略其他的验证 guid := "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" // 计算Sec-WebSocket-Accept h := sha1.New() log.Println("accept raw:", secWebsocketKey + guid) io.WriteString(h, secWebsocketKey + guid) accept := make([]byte, 28) base64.StdEncoding.Encode(accept, h.Sum(nil)) log.Println(string(accept)) response := "HTTP/1.1 101 Switching Protocols\r\n" response = response + "Sec-WebSocket-Accept: " + string(accept) + "\r\n" response = response + "Connection: Upgrade\r\n" response = response + "Upgrade: websocket\r\n\r\n" log.Println("response:", response) if lenth, err := conn.Write([]byte(response)); err != nil { log.Println(err) }else { log.Println("send len:", lenth) } wssocket := NewWsSocket(conn) for { data, err := wssocket.ReadIframe() if err != nil { log.Println("readIframe err:" , err) } log.Println("read data:", string(data)) err = wssocket.SendIframe([]byte("good")) if err != nil { log.Println("sendIframe err:" , err) } log.Println("send data") } }else { log.Println(string(content)) // 直接读取 } } type WsSocket struct { MaskingKey []byte Conn net.Conn } func NewWsSocket(conn net.Conn) *WsSocket { return &WsSocket{Conn: conn} } func (this *WsSocket)SendIframe(data .........完整代码请登录后点击上方下载按钮下载查看
网友评论0