mirror of https://gitee.com/topnuomi/goweb
117 lines
2.5 KiB
Go
117 lines
2.5 KiB
Go
package websocket
|
||
|
||
import (
|
||
"encoding/json"
|
||
"fmt"
|
||
"log"
|
||
"net"
|
||
"net/http"
|
||
"site/core"
|
||
"site/utils/tcp"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
"github.com/gorilla/websocket"
|
||
)
|
||
|
||
type ImController struct {
|
||
core.Controller
|
||
WsManager *core.WebSocketConnManager
|
||
}
|
||
|
||
func NewImController() *ImController {
|
||
return &ImController{
|
||
WsManager: core.NewWebSocketConnManager(),
|
||
}
|
||
}
|
||
|
||
func (ic *ImController) Register(r *gin.RouterGroup) {
|
||
r.GET("/ws", ic.WebSocketServer)
|
||
}
|
||
|
||
type TcpData struct {
|
||
ConnId string `json:"conn_id"`
|
||
Message string `json:"message"`
|
||
}
|
||
|
||
func init() {
|
||
// 创建一个TCP服务,作为数据发送接口
|
||
go func() {
|
||
tcp.NewServer().Listen("127.0.0.1:8081", func(conn net.Conn) {
|
||
// 从连接读取数据
|
||
buf := make([]byte, 1024)
|
||
n, err := conn.Read(buf)
|
||
if err != nil {
|
||
log.Println("read error:", err)
|
||
}
|
||
// 解析数据
|
||
var data TcpData
|
||
err = json.Unmarshal(buf[:n], &data)
|
||
if err != nil {
|
||
log.Println("json unmarshal error:", err)
|
||
}
|
||
// 发送数据到所有WebSocket连接
|
||
wsManage := core.NewWebSocketConnManager()
|
||
wsConn, ok := wsManage.GetConn(data.ConnId)
|
||
if ok {
|
||
fmt.Printf("conn: %v\n", wsConn)
|
||
}
|
||
})
|
||
}()
|
||
}
|
||
|
||
// WebSocket服务
|
||
func (ic *ImController) WebSocketServer(c *gin.Context) {
|
||
upgrader := &websocket.Upgrader{
|
||
CheckOrigin: func(r *http.Request) bool {
|
||
return true
|
||
},
|
||
}
|
||
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
|
||
if err != nil {
|
||
http.NotFound(c.Writer, c.Request)
|
||
}
|
||
|
||
// 生成连接ID并加入到管理器
|
||
connId := ic.UUID()
|
||
ic.WsManager.AddConn(connId, conn)
|
||
ic.WsManager.SendMessageToUser(connId, []byte("连接ID: "+connId))
|
||
ic.WsManager.SendMessageToAll([]byte("用户" + connId + "上线了"))
|
||
|
||
defer ic.closeWebSocketConn(connId)
|
||
|
||
log.Printf("连接已建立,连接ID:%s", connId)
|
||
|
||
go func() {
|
||
tcpConn, err := net.Dial("tcp", "127.0.0.1:8081")
|
||
if err != nil {
|
||
log.Println("tcp dial error:", err)
|
||
}
|
||
defer tcpConn.Close()
|
||
td := TcpData{
|
||
ConnId: connId,
|
||
Message: "hello tcp",
|
||
}
|
||
sd, _ := json.Marshal(td)
|
||
tcpConn.Write([]byte(sd))
|
||
}()
|
||
|
||
for {
|
||
_, msg, err := conn.ReadMessage()
|
||
if err != nil {
|
||
ic.closeWebSocketConn(connId)
|
||
break
|
||
}
|
||
log.Println("客户端" + connId + "消息:" + string(msg))
|
||
}
|
||
}
|
||
|
||
// 关闭连接
|
||
func (ic *ImController) closeWebSocketConn(connId string) {
|
||
conn, ok := ic.WsManager.GetConn(connId)
|
||
if ok {
|
||
log.Printf("连接已关闭,连接ID:%s", connId)
|
||
conn.Close()
|
||
ic.WsManager.RemoveConn(connId)
|
||
}
|
||
}
|