使用Go语言实现WebSocket消息发送案例

摘要

本文将使用Go语言 gorilla/websocket 库在线实现一个基于WebSocket的消息发送的案例,我们将建立一个简单的服务端用于回播我们向它发送的一切消息。本案例可在线运行,以便于--新消息频 道更好的理解go语言的使用以及WebSocket的实际应用。

WebSocket简介

因为HTTP协议是非持久化的,单向的网络协议,是不支持长连接的,在建立连接后只允许浏览器向服务器发出请求后,服务器才能返回相应的数据。之前要实现实时的通信,采用是下图左方的轮询方式,资源消耗非常大。

从HTML5开始提供的一种浏览器与服务器进行全双工通讯的网络技术,属于应用层协议。它基于TCP传输协议,并复用HTTP的握手通道。WebSocket简单的来讲,就是可以在浏览器里支持双向通信。

正文

Go语言环境准备

请前往该页完成安装后返回本页进行下一步。

go环境安装新消息频道 提供)

准备gorilla/websocket 库

go get github.com/gorilla/websocket

language-bash

WebSocket服务端文件

cd ~
cat > websockets.go << EOF
// websockets.go
package main
 
import (
    "fmt"
    "net/http"
    "github.com/gorilla/websocket"
)
 
var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
}
 
func main() {
    http.HandleFunc("/echo", func(w http.ResponseWriter, r *http.Request) {
        conn, _ := upgrader.Upgrade(w, r, nil) // error ignored for sake of simplicity
 
        for {
            // Read message from browser
            msgType, msg, err := conn.ReadMessage()
            if err != nil {
                return
            }
 
            // Print the message to the console
            fmt.Printf("%s sent: %s\n", conn.RemoteAddr(), string(msg))
 
            // Write message back to browser
            if err = conn.WriteMessage(msgType, msg); err != nil {
                return
            }
        }
    })
 
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "websockets.html")
    })
 
    http.ListenAndServe(":80", nil)
}
EOF

WebSocket客户端文件

cd ~
cat > websockets.html << EOF
<!-- websockets.html -->
<input id="input" type="text" />
<button onclick="send()">Send</button>
<pre id="output"></pre>
<script>
    var input = document.getElementById("input");
    var output = document.getElementById("output");
    var socket = new WebSocket("ws://localhost:80/echo");
 
    socket.onopen = function () {
        output.innerHTML += "Status: Connected\n";
    };
 
    socket.onmessage = function (e) {
        output.innerHTML += "Server: " + e.data + "\n";
    };
 
    function send() {
        socket.send(input.value);
        input.value = "";
    }
</script>
EOF

运行验证

在右侧实验区打开+号下的open vnc后,在桌面下新建一个终端,运行~/firefox/firefox,打开FireFox,输入localhost即可看到使用的效果。

完结

以上就是使用Go语言实现WebSocket消息发送案例的所有内容,欢迎小伙伴们交流讨论。

相关文章

Golang的文档和社区资源:为什么它可以帮助开发人员快速上手...
Golang:AI 开发者的实用工具
Golang的标准库:为什么它可以大幅度提高开发效率?
Golang的部署和运维:如何将应用程序部署到生产环境中?
高性能AI开发:Golang的优势所在
本篇文章和大家了解一下go语言开发优雅得关闭协程的方法。有...