Go语言github.com/gorilla/websocket框架websocket协议通信实战

      websocket是实际开发中比较常用的应用层协议,本文利用github.com/gorilla/websocket框架进行websocket通信实战。

目录

1.下载github.com/gorilla/websocket

2.websocket服务端

3.websocket Go客户端

4.websocket 网页客户端

5.运行结果展示


1.下载github.com/gorilla/websocket

go get github.com/gorilla/websocket

2.websocket服务端

package main

import (
	"log"
	"net/http"
	"strings"
	"unsafe"

	"github.com/gorilla/websocket"
)

/*
go get github.com/gorilla/websocket
*/

/*
	var upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}
*/
var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func handleWebsocket(w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println(err)
		return
	}
	defer conn.Close()

	for {
		messageType, p, err := conn.ReadMessage()
		if err != nil {
			log.Println(err)
			return
		}

		/*
			// 字节转字符串
			fmt.Println(string(p))
			fstr := *(*string)(unsafe.Pointer(&p))
			fmt.Println(fstr)
		*/

		/*
			// 字符串转字节
			fmt.Println(*(*[]byte)(unsafe.Pointer(&fstr)))
		*/

		log.Printf("received: %s", p)

		//lower := strings.ToLower(fstr)
		//字符串转大写
		fstr := *(*string)(unsafe.Pointer(&p))
		upperStr := strings.ToUpper(fstr)

		err = conn.WriteMessage(messageType, *(*[]byte)(unsafe.Pointer(&upperStr)))
		if err != nil {
			log.Println(err)
			return
		}
	}
}

func main() {
	http.HandleFunc("/ws", handleWebsocket)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

3.websocket Go客户端

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/gorilla/websocket"
)

func test() {
	// 连接WebSocket服务器
	conn, _, err := websocket.DefaultDialer.Dial("ws://localhost:8080/ws", nil)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	// 发送消息
	err = conn.WriteMessage(websocket.TextMessage, []byte("Hello, world!"))
	if err != nil {
		log.Fatal(err)
	}

	// 读取消息
	messageType, p, err := conn.ReadMessage()
	if err != nil {
		log.Fatal(err)
	}
	log.Println("Received message:", string(p), messageType)
}

func test1() int {
	// 连接WebSocket服务器
	conn, _, err := websocket.DefaultDialer.Dial("ws://localhost:8080/ws", nil)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	reader := bufio.NewReader(os.Stdin)
	for {
		data, err := reader.ReadString('\n')
		if err != nil {
			fmt.Printf("read from console failed, err:%v\n", err)
			break
		}

		data = strings.TrimSpace(data)

		// 发送消息
		err = conn.WriteMessage(websocket.TextMessage, []byte(data))
		if err != nil {
			log.Fatal(err)
		}

		// 读取消息
		messageType, p, err := conn.ReadMessage()
		if err != nil {
			log.Fatal(err)
		}
		log.Println("received: ", string(p), messageType)
	}

	return 0
}

func main() {
	test1()
}

4.websocket 网页客户端



  
    
    Websockets Example
  
  
    
    
    

    5.运行结果展示

    服务器:

    Go语言github.com/gorilla/websocket框架websocket协议通信实战_第1张图片

     Go语言客户端:

    Go语言github.com/gorilla/websocket框架websocket协议通信实战_第2张图片

     Web客户端:

    Go语言github.com/gorilla/websocket框架websocket协议通信实战_第3张图片

     


     

    你可能感兴趣的:(golang,golang,websocket)