设为首页 加入收藏

TOP

浏览器与go语言的websocket通信
2018-12-12 18:10:37 】 浏览:156
Tags:浏览器 语言 websocket 通信

简介
WebSocket是HTML5一种新的协议。顾名思义,它在服务器和浏览器之间建立了全双工通信。

需求背景
区块链测试系统web前端平台需要动态接收后端发送的状态信息改变一次测试session过程的状态显示,测试用例在运行后会返回一次运行的session,后端根据该session实时返回测试状态。

思路过程:
1.找到go语言websocket官方文档github官方地址https://github.com/gorilla/websocket
2.git clone代码,运行官方用例教程server
3.前端使用h5的websocket服务访问server
4.根据项目需求封装接口



bug踩坑:
1.can't load package: package server: build constraints exclude all Go files in /home/zeng/go-websocket/src/server
去掉  // +build ignore 即可

2.Firefox 无法建立到 ws://localhost:8080/echo 服务器的连接。
server配置跨域访问
var upgrader = websocket.Upgrader{
    // 解决跨域问题
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

前端主要代码:
<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>
</head>
<body>
<h1>WebSocket</h1>
<script>
    var websocket  = new WebSocket("ws://localhost:8080/echo");
    websocket.onopen = function () {
        session = "abcd"
        websocket.send(session);
        console.log(websocket.readyState)
    }
    websocket.onmessage = function (event) {
        console.log(event.data);
        websocket.close()
    }
    websocket.onclose = function() {
        alert("连接已关闭...");
    };
</script>
</body>
</html>

后端主要代码:
package main

import (
    "SocketService"
    "encoding/json"
    "fmt"
    "time"
)

type Test struct {
    Id   string
    Data string
}

func main() {
    url := "localhost:8080"
    SocketService.Init(url)
    time.Sleep(time.Second * 10)
    err := SocketService.SendMessage("abc", []byte("zeng"))
    if err != nil {
        fmt.Println("1:", err)
    }
    t := Test{"Id", "Data"}
    d, _ := json.Marshal(t)
    session := "abcd"
    SocketService.SendMessage(session, d)

    if err != nil {
        fmt.Println("2:", err)
    }
    time.Sleep(time.Second * 1000)

}


参考博客:
https://blog.csdn.net/imliutao2/article/details/80838975
https://blog.csdn.net/wang_gongzi/article/details/82860427

demo传送门:https://github.com/umbrellahusky/gowebsocket

邮箱:2919033008@qq.com
qq:2919033008

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Golang-map 下一篇数据流中的第k大元素的golang实现

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目