17

GO和WebSocket,快速开始

 3 years ago
source link: https://studygolang.com/articles/31605
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

WebSocket

WebSocket是基于TCP的通讯方式,后面我们简称ws

在HTML5中,使用WebSocket可以跳过HTTP协议进行有状态的通信。

WebSocket传输支持字符串、Blob、ArrayBuffer等。

对于Golang-gorilla来说就是String或[]byte

JS&GO Hello WebSocket

JavaScript

需要对H5支持较好的游览器才可以正常的进行ws通讯。

if ("WebSocket" in window){
    //如果支持那么执行
}

我们先看js代码,基本上就是顾名思义了。

<script>
var ws = new WebSocket("ws://localhost:6060/ws");  
//连接打开时触发 
ws.onopen = function(evt) {  
    console.log("Connection open ...");  
    ws.send("Hello WebSockets1!");  
    ws.send("Hello WebSockets2!"); 
    ws.send("Hello WebSockets3!"); 
    ws.send("Hello WebSockets4!");  
    //如果我们一定时间不通信,TCP就会断开,无论我们是否手动断开
    //ws.close();   
};  
//接收到消息时触发  
ws.onmessage = function(evt) {  
    console.log("Received Message: " + evt.data);  
};  
//连接关闭时触发  
ws.onclose = function(evt) {  
    console.log("Connection closed.");  
};  
</script>

GO

引入包

import "github.com/gorilla/websocket"

这里用了gin框架,其实net/http更适合websocket

r := gin.Default()
    r.Any("/ws",func(c *gin.Context){
        //1.设置websocket参数,CheckOrigin表示是否允许跨域
        upgrader:=websocket.Upgrader{CheckOrigin:func(r *http.Request)bool{
            return true
        }}
        //2.建立websocket连接
        conn,err:=upgrader.Upgrade(c.Writer,c.Request,nil)
        defer conn.Close()
        if err!=nil{
            fmt.Println(err)
            return
        }
        for{
            //对接受数据处理
            //第一个参数是数据类型,只是一个int,1代表String,2代表[]byte
            _,data,err:=conn.ReadMessage()
            if err!=nil{
                fmt.Println(err)
                return
            }
            err=conn.WriteMessage(websocket.TextMessage,data)
            if err!=nil{
                fmt.Println(err)
                return
            }
        }


    })
    r.Run(":6060")

运行效果

viyIfmr.jpg!mobile

chrome控制台

我发现这里结果少了一句Connection closed.可是server已经显示断开了,可能是服务器造成的意外关闭并不会执行js中的onclose方法。

下次我们可以讲讲,怎么避免超时关闭和更严谨的ws通信。

有疑问加站长微信联系(非本文作者)

eUjI7rn.png!mobile

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK