37 lines
931 B
Go
37 lines
931 B
Go
package util
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gorilla/websocket"
|
|
)
|
|
|
|
func GetWebsocket(AppId, ServerId int) (*websocket.Conn, error) {
|
|
ServerConfig, err := GetServerConfig(AppId, ServerId)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to get server config: %v", err)
|
|
}
|
|
if ServerConfig == nil {
|
|
return nil, fmt.Errorf("server config not found for AppId %d and ServerId %d", AppId, ServerId)
|
|
}
|
|
nodeConfig := GetNodeById(ServerConfig.ECS)
|
|
url := fmt.Sprintf("ws://%s:%d/", nodeConfig.Host, ServerConfig.WsPort)
|
|
// if common.GetEnv() == "dev" {
|
|
// url = "ws://127.0.0.1:3567/" // 本地调试使用内网地址
|
|
// }
|
|
dialer := &websocket.Dialer{
|
|
HandshakeTimeout: 5 * time.Second,
|
|
}
|
|
|
|
header := http.Header{}
|
|
header.Set("Origin", "http://localhost/")
|
|
|
|
ws, _, err := dialer.Dial(url, header)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to connect to websocket: %v", err)
|
|
}
|
|
return ws, nil
|
|
}
|