Skip to content

Commit

Permalink
全员发送消息 http接口
Browse files Browse the repository at this point in the history
接收消息显示界面
  • Loading branch information
link1st committed Aug 1, 2019
1 parent 6c17cf5 commit fccd9d4
Show file tree
Hide file tree
Showing 10 changed files with 428 additions and 286 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,5 @@ govendor add -tree github.com/spf13/viper
- html接收到消息 显示到界面
- 界面优化
- 有人加入以后广播全体
- 定义加入聊天室的消息结构
- 定义加入聊天室的消息结构
- 引入机器人
10 changes: 10 additions & 0 deletions controllers/base_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@ type BaseController struct {
// 获取全部请求解析到map
func Response(c *gin.Context, code int, msg string, data map[string]interface{}) {
message := common.Response(code, msg, data)

// 允许跨域
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Origin", "*") // 这是允许访问所有域
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") // 服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求
c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar") // 跨域关键设置 让浏览器可以解析
c.Header("Access-Control-Allow-Credentials", "true") // 跨域请求是否需要带cookie信息 默认设置为true
c.Set("content-type", "application/json") // 设置返回格式是json

c.JSON(http.StatusOK, message)

return
Expand Down
28 changes: 25 additions & 3 deletions controllers/user/user_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,16 @@ func SendMessage(c *gin.Context) {
// 获取参数
appIdStr := c.PostForm("appId")
userId := c.PostForm("userId")
msgId := c.PostForm("msgId")
message := c.PostForm("message")

fmt.Println("http_request 给用户发送消息", appIdStr, userId, message)
fmt.Println("http_request 给用户发送消息", appIdStr, userId, msgId, message)

appId, _ := strconv.ParseInt(appIdStr, 10, 32)

data := make(map[string]interface{})

sendResults, err := users.SendUserMessage(uint32(appId), userId, message)
sendResults, err := users.SendUserMessage(uint32(appId), userId, msgId, message)
if err != nil {
data["sendResultsErr"] = err.Error()

Expand All @@ -58,7 +59,28 @@ func SendMessage(c *gin.Context) {
controllers.Response(c, common.OK, "", data)
}

// 给全体用户发送消息
// 给全员发送消息
func SendMessageAll(c *gin.Context) {
// 获取参数
appIdStr := c.PostForm("appId")
userId := c.PostForm("userId")
msgId := c.PostForm("msgId")
message := c.PostForm("message")

fmt.Println("http_request 给全体用户发送消息", appIdStr, userId, msgId, message)

appId, _ := strconv.ParseInt(appIdStr, 10, 32)

data := make(map[string]interface{})

sendResults, err := users.SendUserMessageAll(uint32(appId), userId, msgId, message)
if err != nil {
data["sendResultsErr"] = err.Error()

}

data["sendResults"] = sendResults

controllers.Response(c, common.OK, "", data)

}
31 changes: 31 additions & 0 deletions models/msg_model.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* Created by GoLand.
* User: link1st
* Date: 2019-08-01
* Time: 10:40
*/

package models

const (
messageTypeText = "text"
)

// 消息的定义
type Message struct {
Target string `json:"target"` // 目标
Type string `json:"type"` // 消息类型 text/img/
Msg string `json:"msg"` // 消息内容
From string `json:"from"` // 发送者
}

func NewTestMsg(from string, Msg string) (message *Message) {

message = &Message{
Type: messageTypeText,
From: from,
Msg: Msg,
}

return
}
21 changes: 0 additions & 21 deletions models/request_model.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,24 +26,3 @@ type Login struct {
type HeartBeat struct {
UserId string `json:"userId,omitempty"`
}

/************************ 响应数据 **************************/
type Head struct {
Seq string `json:"seq"` // 消息的Id
Cmd string `json:"cmd"` // 消息的cmd
Response Response `json:"response"` // 消息体
}

type Response struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"` // 数据 json
}

// push 数据结构体
type PushMsg struct {
Seq string `json:"seq"`
Uuid uint64 `json:"uuid"`
Type string `json:"type"`
Msg string `json:"msg"`
}
49 changes: 49 additions & 0 deletions models/response_model.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* Created by GoLand.
* User: link1st
* Date: 2019-08-01
* Time: 10:46
*/

package models

import "encoding/json"

/************************ 响应数据 **************************/
type Head struct {
Seq string `json:"seq"` // 消息的Id
Cmd string `json:"cmd"` // 消息的cmd
Response *Response `json:"response"` // 消息体
}

type Response struct {
Code int `json:"code"`
CodeMsg string `json:"codeMsg"`
Data interface{} `json:"data"` // 数据 json
}

// push 数据结构体
type PushMsg struct {
Seq string `json:"seq"`
Uuid uint64 `json:"uuid"`
Type string `json:"type"`
Msg string `json:"msg"`
}

// 设置返回消息
func NewResponseHead(seq string, cmd string, code int, codeMsg string, data interface{}) *Head {
response := NewResponse(code, codeMsg, data)

return &Head{Seq: seq, Cmd: cmd, Response: response}
}

func (h *Head) String() (headStr string) {
headBytes, _ := json.Marshal(h)
headStr = string(headBytes)

return
}

func NewResponse(code int, codeMsg string, data interface{}) *Response {
return &Response{Code: code, CodeMsg: codeMsg, Data: data}
}
29 changes: 25 additions & 4 deletions servers/users/user_srv.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ import (
"errors"
"fmt"
"github.com/go-redis/redis"
"gowebsocket/common"
"gowebsocket/lib/cache"
"gowebsocket/models"
"gowebsocket/servers/websocket"
)

Expand Down Expand Up @@ -54,10 +56,12 @@ func checkUserOnline(appId uint32, userId string) (online bool, err error) {
}

// 给用户发送消息
func SendUserMessage(appId uint32, userId string, message string) (sendResults bool, err error) {
func SendUserMessage(appId uint32, userId string, msgId, message string) (sendResults bool, err error) {

data := getTextMsgData(userId, msgId, message)

// TODO::需要判断不在本机的情况
sendResults, err = sendUserMessageLocal(appId, userId, message)
sendResults, err = sendUserMessageLocal(appId, userId, data)
if err != nil {
fmt.Println("给用户发送消息", appId, userId, err)
}
Expand All @@ -66,7 +70,7 @@ func SendUserMessage(appId uint32, userId string, message string) (sendResults b
}

// 给本机用户发送消息
func sendUserMessageLocal(appId uint32, userId string, message string) (sendResults bool, err error) {
func sendUserMessageLocal(appId uint32, userId string, data string) (sendResults bool, err error) {

client := websocket.GetUserClient(appId, userId)
if client == nil {
Expand All @@ -76,8 +80,25 @@ func sendUserMessageLocal(appId uint32, userId string, message string) (sendResu
}

// 发送消息
client.SendMsg([]byte(message))
client.SendMsg([]byte(data))
sendResults = true

return
}

// 给全体用户发消息
func SendUserMessageAll(appId uint32, userId string, msgId, message string) (sendResults bool, err error) {
sendResults = true

data := getTextMsgData(userId, msgId, message)
websocket.AllSendMessages(appId, userId, data)

return
}

func getTextMsgData(uuId, msgId, message string) string {
textMsg := models.NewTestMsg(uuId, message)
head := models.NewResponseHead(msgId, "msg", common.OK, "Ok", textMsg)

return head.String()
}
16 changes: 2 additions & 14 deletions servers/websocket/acc_process.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,6 @@ func ProcessData(client *Client, message []byte) {
seq := request.Seq
cmd := request.Cmd

// 返回数据
head := &models.Head{
Seq: seq,
Cmd: cmd,
}

var (
code int
msg string
Expand All @@ -97,15 +91,9 @@ func ProcessData(client *Client, message []byte) {

msg = common.GetErrorMessage(code, msg)

response := models.Response{
Code: code,
Msg: msg,
Data: data,
}

head.Response = response
responseHead := models.NewResponseHead(seq, cmd, code, msg, data)

headByte, err := json.Marshal(head)
headByte, err := json.Marshal(responseHead)
if err != nil {
fmt.Println("处理数据 json Marshal", err)

Expand Down
10 changes: 9 additions & 1 deletion servers/websocket/client_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ func (manager *ClientManager) DelUsers(key string) {
}

// 向全部成员(除了自己)发送数据
func (manager *ClientManager) send(message []byte, ignore *Client) {
func (manager *ClientManager) sendAll(message []byte, ignore *Client) {
for conn := range manager.Clients {
if conn != ignore {
conn.Send <- message
Expand Down Expand Up @@ -227,3 +227,11 @@ func ClearTimeoutConnections() {
}
}
}

// 全员广播
func AllSendMessages(appId uint32, userId string, data string) {
fmt.Println("全员广播", appId, userId, data)

ignore := clientManager.GetUserClient(appId, userId)
clientManager.sendAll([]byte(data), ignore)
}
Loading

0 comments on commit fccd9d4

Please sign in to comment.