This commit is contained in:
laodaming 2023-08-23 16:57:18 +08:00
parent b68da2e68a
commit 500611236e
2 changed files with 28 additions and 6 deletions

View File

@ -6,6 +6,8 @@ type Websocket string
const (
//鉴权失败
WEBSOCKET_UNAUTH Websocket = "WEBSOCKET_UNAUTH"
//获取ws连接标识错误
WEBSOCKET_GEN_UNIQUE_ID_ERR Websocket = "WEBSOCKET_GEN_UNIQUE_ID_ERR"
//ws连接成功
WEBSOCKET_CONNECT_SUCCESS Websocket = "WEBSOCKET_CONNECT_SUCCESS"
//请求恢复为上次连接的标识

View File

@ -106,7 +106,10 @@ func (l *DataTransferLogic) DataTransfer(w http.ResponseWriter, r *http.Request)
return
}
//设置连接
ws := l.setConnPool(conn, *userInfo)
ws, err := l.setConnPool(conn, *userInfo)
if err != nil {
return
}
defer ws.close()
//循环读客户端信息
go ws.readLoop()
@ -123,11 +126,16 @@ func (l *DataTransferLogic) DataTransfer(w http.ResponseWriter, r *http.Request)
}
// 设置连接
func (l *DataTransferLogic) setConnPool(conn *websocket.Conn, userInfo auth.UserInfo) wsConnectItem {
func (l *DataTransferLogic) setConnPool(conn *websocket.Conn, userInfo auth.UserInfo) (wsConnectItem, error) {
publicMutex.Lock()
defer publicMutex.Unlock()
//生成连接唯一标识
uniqueId := l.getUniqueId(userInfo)
uniqueId, err := l.getUniqueId(userInfo)
if err != nil {
//发送获取唯一标识失败的消息
l.sendGetUniqueIdErrResponse(conn)
return wsConnectItem{}, err
}
ws := wsConnectItem{
conn: conn,
logic: l,
@ -155,7 +163,7 @@ func (l *DataTransferLogic) setConnPool(conn *websocket.Conn, userInfo auth.User
time.Sleep(time.Second * 1) //兼容下火狐(直接发回去收不到第一条消息:有待研究)
ws.sendToOutChan(ws.respondDataFormat(constants.WEBSOCKET_CONNECT_SUCCESS, uniqueId))
}()
return ws
return ws, nil
}
// 获取唯一id
@ -214,8 +222,20 @@ func (l *DataTransferLogic) unAuthResponse(conn *websocket.Conn) {
_ = conn.WriteMessage(websocket.TextMessage, b)
//发送关闭信息
_ = conn.WriteMessage(websocket.CloseMessage, nil)
//关闭连接
conn.Close()
}
// 获取唯一标识失败通知
func (l *DataTransferLogic) sendGetUniqueIdErrResponse(conn *websocket.Conn) {
time.Sleep(time.Second * 1) //兼容下火狐(直接发回去收不到第一条消息:有待研究)
rsp := websocket_data.DataTransferData{
T: constants.WEBSOCKET_GEN_UNIQUE_ID_ERR,
D: "err to gen unique id ",
}
b, _ := json.Marshal(rsp)
//先发一条正常信息
_ = conn.WriteMessage(websocket.TextMessage, b)
//发送关闭信息
_ = conn.WriteMessage(websocket.CloseMessage, nil)
}
// 心跳检测