设为首页 加入收藏

TOP

Golang websocket推送(二)
2019-05-23 14:35:39 】 浏览:204
Tags:Golang websocket 推送
g); err != nil { fmt.Println("Send msg error: ", err) } } else { fmt.Println("invalid type, expect *websocket.Conn") } } else { fmt.Println("connection not exist") } } } // broadcast message to all websocket connections otherwise own connection func (m *ConnManager) Broadcast(conn *websocket.Conn, msg *Message) { m.Foreach(func(k, v interface{}) { if c, ok := v.(*websocket.Conn); ok && c != conn { if err := websocket.JSON.Send(c, msg); err != nil { fmt.Println("Send msg error: ", err) } } }) }

消息类型、格式

消息类型(MessageType)主要有单聊、群聊、系统通知等。

消息格式(MediaType)主要有文本格式、图片、文件等。

type MessageType int
type MediaType int

const (
    Single MessageType = iota
    Group
    SysNotify
    OnlineNotify
    OfflineNotify
)

const (
    Text MediaType = iota
    Image
    File
)

// websocket message
type Message struct {
    MessageType MessageType `json:"messageType"`
    MediaType   MediaType   `json:"mediaType"`
    From        string      `json:"from"`
    To          string      `json:"to"`
    Content     string      `json:"content,omitempty"`
    FileId      string      `json:"fileId,omitempty"`
    Url         string      `json:"url,omitempty"`
    CreateAt    int64       `json:"createAt,omitempty"`
    UpdateAt    int64       `json:"updateAt,omitempty"`
}

上面定义了一个统一的消息(Message)。

效果

前端的代码就不展示了,最终实现的聊天室效果如下:

UI

补充

本例子没有涉及到用户认证、消息加密、idle、单聊、消息格式、消息持久化等等,只做了一个简单的群聊。

欢迎感兴趣的道友,基于此扩展出自己的推送系统、IM等。

说明

Just for fun!

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇golang channel 源码剖析 下一篇go 调用windows dll 的方法

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目