golang网络编程学习-websocket

golang网络编程学习-websocket

网络编程主要的内容是:
1.TCP网络编程
2.http服务
3.rpc服务
4.websocket服务

 一、websocket编程

1.1服务端,代码来自网络,仅限于学习研究

package main

import (
	"fmt"
	"net/http"
	"os"
	"reflect"
	"time"
	"unsafe"

	"github.com/gorilla/websocket"
)

type HttpHandler struct {
	http.Handler
}

func main() {
	var httpHandler HttpHandler
	http.Handle("/connect", httpHandler)
	if err := http.ListenAndServe(":9999", nil); err != nil {
		fmt.Println("程序退出")
		os.Exit(1)
	}
}

func (httpHandler HttpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Println("程序进入监听>>")
	var upgrader = websocket.Upgrader{
		//解决跨域问题
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		fmt.Println("upgrade error:", err)
		return
	}
	defer conn.Close()
	conn.SetReadDeadline(time.Now().Add(6 * time.Second))
	conn.SetPongHandler(func(string) error {
		fmt.Println("接收心跳响应<<")
		conn.SetReadDeadline(time.Now().Add(6 * time.Second))
		return nil
	})
	ticker := time.NewTicker(2 * time.Second)
	go func() {
		for {
			//从定时器中获取数据
			_ = <-ticker.C
			fmt.Println("发送心跳包>>")
			conn.WriteMessage(websocket.PingMessage, []byte{})
		}
	}()
	defer ticker.Stop()
	for {
		messageType, message, err := conn.ReadMessage()
		if err != nil {
			fmt.Println("接收异常:", err)
			break
		}
		fmt.Println(fmt.Sprintf("接收消息内容 >>%s", message))
		respMessage := fmt.Sprintf("I am Server, %s.", time.Now().Format("2006-01-02 15:04:05"))
		err = conn.WriteMessage(messageType, String2Bytes(respMessage))
		if err != nil {
			fmt.Println("发送异常:", err)
			break
		}
	}
}

func String2Bytes(s string) []byte {
	sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
	bh := reflect.SliceHeader{
		Data: sh.Data,
		Len:  sh.Len,
		Cap:  sh.Len,
	}
	return *(*[]byte)(unsafe.Pointer(&bh))
}

 

服务端截图

golang网络编程学习-websocket_第1张图片

 

1.2客户端,代码来自网络,仅限于学习研究



    


未连接

golang网络编程学习-websocket_第2张图片

 

golang网络编程学习-websocket_第3张图片

 

 客户端浏览器运行内容信息

 golang网络编程学习-websocket_第4张图片

 

你可能感兴趣的:(golang30天,golang,学习,websocket)