1. 程式人生 > 其它 >websocket訊息推送 Go websocket訊息推送服務

websocket訊息推送 Go websocket訊息推送服務

https://studygolang.com/p/go-websocket

簡介

golang websocket 服務可通過http介面push訊息到web客戶端,訊息傳送採用golang的併發模式傳送,並非同步記錄傳送的訊息日誌。

安裝

  • 匯入 db.sql 安裝相關push日誌表
  • 更改 config.dev.json中的相關db配置與專案路徑配置
  • 執行 install_package.sh 安裝相關包依賴
  • 執行 go build -o build/push_service
  • 執行 build/push_service dev

注意

本專案websocket使用使用者token驗證連線,這一塊驗證的邏輯需要根據自己的業務去更改或刪除。 可聯絡我進行付費二次開發。

使用

例如使用PHP客戶端push訊息

<?php
/**
 * Created by PhpStorm.
 * Date: 2019/5/23
 * Time: 17:03
 */

require_once 'XHXPushApi.php';

$title = "通知標題pxy";
$content = "測試通知內容,測試通知內容,測試通知內容,測試通知內容,測試通知內容,測試通知內容。";

/**  push介面支援的引數
     * @param $senderId      //傳送者id
     * @param $senderName    //傳送者姓名
     * @param $msgType       //訊息型別 1傳送線上使用者即時訊息 2登入後必達訊息 3業務內容更新訊息
     * @param $title         //訊息標題
     * @param $content       //訊息內容陣列或字串,如果是陣列將會被json_encode
     * @param $userIds       //使用者id以,號分隔 msgType為2時userIds必傳
     * @param $options       //彈窗選專案前支援 duration(毫秒), position, type引數(對應elementUi通知元件引數)
     * @return array
*/
$res = XHXPushApi::getInstance()->push(1,'god', 2, $title, $content, [44, 63]);

print_r($res);

client.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <!-- import CSS -->
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
  <div id="app">

  </div>
</body>
  <!-- import Vue before Element -->
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
  <!-- import JavaScript -->
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
  <script>
    new Vue({
      el: '#app',
      data() {
        return { 
            visible: false,
            ws:'',
            interval:'',
            retryConnect:false,
        }
      },
      created() {
          this.init()
      },
      methods: {
        init() {
            if (!window["WebSocket"]) {
                console.log('not support websocket')
                return
            }

            var that = this;
            this.ws = new WebSocket("ws://127.0.0.1:9002/ws/");
            this.ws.onclose = function(e) {
                clearInterval(that.interval)
                if(!that.retryConnect) {
                    return
                }
                console.log('push connection is close, retry connect after 5 seconds')
                setTimeout(function() {
                    that.init()
                }, 5000);
            }
            this.ws.addEventListener('open', function (e) {
                //登入
                that.ws.send('{"event":"register", "token":"00000063_d10f2dd30c087a0573d54e4767640253279"}');
            });

            this.ws.addEventListener("message", function(e) {
                let res = JSON.parse(e.data)

                //token過期
                if(res.error == 100) {
                    console.log(res)
                    that.retryConnect = false
                    return
                }

                if(res.error != 0) {
                    console.log(res.msg)
                    return
                }

                //client註冊訊息
                if(res.event == 'register') {
                    console.log('ws connection register success ')
                    that.interval = setInterval(function() {
                        //保此常連線心跳
                        that.ws.send('{}')
                    }, 60000)
                    that.retryConnect = true
                    return;
                }

                if(res.event == 'message') {
                    let options = JSON.parse(res.data.options);
                    that.$notify.info({
                        title: res.data.title != '' ? res.data.title : '通知',
                        message: res.data.content,
                        duration: options.duration,
                        position: options.position
                    });
                }
            })
        }
      }
    })
  </script>
</html>

jack15083/go-websocket-broadcast

3410

Go 語言 + Redis + DB實現的websocket 廣播訊息推送服務。—Read More

Latest commit to themasterbranch on 7-16-2020 Download as zip
授權協議:
MIT
開發語言:
golang檢視原始碼»
作業系統:
linux/windows/unix