0


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

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

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 网页客户端

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Websockets Example</title>
  </head>
  <body>
    <input id="message-input" type="text" placeholder="please input a message">
    <button id="send-button">发送</button>
    <ul id="message-list"></ul>
    <script>
      const socket = new WebSocket('ws://localhost:8080/ws');
      socket.addEventListener('message', event => {
        const li = document.createElement('li');
        li.textContent = event.data;
        document.querySelector('#message-list').appendChild(li);
      });
      document.querySelector('#send-button').addEventListener('click', () => {
        const input = document.querySelector('#message-input');
        const value = input.value.trim();
        if (value) {
          socket.send(value);
          input.value = '';
        }
      });
    </script>
  </body>
</html>

5.运行结果展示

服务器:

Go语言客户端:

Web客户端:

标签: golang websocket

本文转载自: https://blog.csdn.net/hsy12342611/article/details/131698876
版权归原作者 hsy12342611 所有, 如有侵权,请联系我们删除。

“Go语言github.com/gorilla/websocket框架websocket协议通信实战”的评论:

还没有评论