4 Star 0 Fork 0

高冠祺/SRS-SERVER-GO

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
main.go 1.69 KB
一键复制 编辑 原始数据 按行查看 历史
高冠祺 提交于 2024-08-30 09:56 . init
package main
import (
"log"
"net/http"
socketio "github.com/googollee/go-socket.io"
)
func withCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Access-Control-Max-Age", "3600")
// Handle preflight requests
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
func main() {
log.Println("go...")
server := socketio.NewServer(nil)
server.OnConnect("/", func(s socketio.Conn) error {
s.SetContext("")
log.Println("Client connected:", s.ID())
return nil
})
server.OnDisconnect("/", func(s socketio.Conn, reason string) {
log.Println("Client disconnected:", s.ID(), "Reason:", reason)
})
server.OnError("/", func(s socketio.Conn, e error) {
log.Println("Socket.IO error for client:", s.ID(), "Error:", e)
})
server.OnEvent("/", "message", func(s socketio.Conn, msg string) {
log.Println("Received message from client:", msg)
s.Emit("response", "Message received: "+msg)
})
go func() {
if err := server.Serve(); err != nil {
log.Fatalf("Socket.IO server failed: %v", err)
}
}()
defer server.Close()
http.Handle("/", withCORS(http.FileServer(http.Dir("./static"))))
http.Handle("/socket.io/", withCORS(server))
ipAddress := "192.168.0.25"
port := "8877"
address := ipAddress + ":" + port
log.Printf("Serving at ws://%s...", address)
if err := http.ListenAndServe(address, nil); err != nil {
log.Fatalf("Failed to start HTTP server: %v", err)
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/qq307590625/srs-server-go.git
git@gitee.com:qq307590625/srs-server-go.git
qq307590625
srs-server-go
SRS-SERVER-GO
master

搜索帮助