Files
webtransport_test/main.go
2026-04-04 14:59:00 +00:00

87 lines
2.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"encoding/json"
"fmt"
"net/http"
//"sync"
"github.com/pion/webrtc/v3"
)
func main() {
// Статический HTML фронтенд
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
})
// Сигналлинг: прием Offer и возврат Answer
http.HandleFunc("/sdp", handleSignaling)
fmt.Println("Server starting on :8080 at auth.shaiheprjct.ru")
http.ListenAndServe(":8080", nil)
}
func handleSignaling(w http.ResponseWriter, r *http.Request) {
var offer webrtc.SessionDescription
if err := json.NewDecoder(r.Body).Decode(&offer); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
config := webrtc.Configuration{
ICEServers: []webrtc.ICEServer{
{
URLs: []string{"stun:88.210.53.29:3478"},
},
{
URLs: []string{"turn:88.210.53.29:3478"},
Username: "shaihe",
Credential: "zaq1xsw2",
CredentialType: webrtc.ICECredentialTypePassword,
},
},
}
peerConnection, err := webrtc.NewPeerConnection(config)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Обработка входящего DataChannel
peerConnection.OnDataChannel(func(d *webrtc.DataChannel) {
fmt.Printf("New DataChannel %s %d\n", d.Label(), d.ID())
d.OnOpen(func() {
fmt.Printf("Data channel '%s' open\n", d.Label())
})
d.OnMessage(func(msg webrtc.DataChannelMessage) {
fmt.Printf("Message from DataChannel '%s': %s\n", d.Label(), string(msg.Data))
// Эхо-ответ (имитация UDP ответа)
d.SendText("Echo: " + string(msg.Data))
})
})
// Установка удаленного описания (Offer)
err = peerConnection.SetRemoteDescription(offer)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Создание Answer
answer, err := peerConnection.CreateAnswer(nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Сбор ICE кандидатов (упрощенно: ждем завершения сбора перед отправкой Answer)
gatherComplete := webrtc.GatheringCompletePromise(peerConnection)
peerConnection.SetLocalDescription(answer)
<-gatherComplete
json.NewEncoder(w).Encode(peerConnection.LocalDescription())
}