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)。
效果
前端的代码就不展示了,最终实现的聊天室效果如下:
补充
本例子没有涉及到用户认证、消息加密、idle、单聊、消息格式、消息持久化等等,只做了一个简单的群聊。
欢迎感兴趣的道友,基于此扩展出自己的推送系统、IM等。
说明
Just for fun!