GO --- 实时通信Melody包的介绍和例子

简介

一个用于Go的极简Websocket框架

Melody是基于 github.com/gorilla/websocket框架的,并抽象处理了里面的繁杂部分。

它可以让你搭建一个实时通讯的app,功能包括:

  • 接口简单易用类似于net/http或Gin。
  • 提供给所有广播以及给选择连接会话广播的简单途径。
  • 消息缓冲区使并发写入变得安全。
  • 自动处理ping/pong和会话超时。
  • 在会话中存储数据。

例子

使用Gin框架完成的聊天室功能

下载依赖包

$ go get -u gopkg.in/olahol/melody.v1
$ go get -u github.com/gin-gonic/gin

main.go

package main

import (
   "github.com/gin-gonic/gin"
   "gopkg.in/olahol/melody.v1"
   "net/http"
)

func main() {
   
   
   r := gin.Default()
   m := melody.New()

   r.GET("/", func(c *gin.Context) {
   
   
      http.ServeFile(c.Writer, c.Request, "index.html")
   })

   r.GET("/ws", func(c *gin.Context) {
   
   
      m.HandleRequest(c.Writer, c.Request)
   })

   m.HandleMessage(func(s *melody.Session, msg []byte) {
   
   
      m.Broadcast(msg)
   })

   r.Run(":5000")
}

index.heml

<html>
  <head>
    <title>Melody example: chatting</title>
  </head>

  <style>
    #chat {
     
     
      text-align: left;
      background: #f1f1f1;
      width: 500px;
      min-height: 300px;
      padding: 20px;
    }
  </style>

  <body>
    <center>
      <h3>Chat</h3>
      <pre id="chat"></pre>
      <input placeholder="say something" id="text" type="text">
    </center>

    <script>
      var url = "ws://" + window.location.host + "/ws";
      var ws = new WebSocket(url);
      var name = "Guest" + Math.floor(Math.random() * 1000);

      var chat = document.getElementById("chat");
      var text = document.getElementById("text");

      var now = function () {
     
     
        var iso = new Date().toISOString();
        return iso.split("T")[1].split(".")[0];
      };

      ws.onmessage = function (msg) {
     
     
        var line =  now() + " " + msg.data + "\n";
        chat.innerText += line;
      };

      text.onkeydown = function (e) {
     
     
        if (e.keyCode === 13 && text.value !== "") {
     
     
          ws.send("<" + name + "> " + text.value);
          text.value = "";
        }
      };

    </script>
  </body>
</html>

展示图:

在这里插入图片描述

使用Gin完成文件的实时监控

下载

$ github.com/fsnotify/fsnotify
$ github.com/gin-gonic/gin
$ gopkg.in/olahol/melody.v1

main.go

package main

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值