wip: 0.2.7

实现了 rtc 握手和打开数据通道
This commit is contained in:
loveuer
2025-05-26 17:40:06 +08:00
parent 5bc695bde3
commit 21287e0874
7 changed files with 194 additions and 97 deletions

View File

@ -28,6 +28,7 @@ func Start(ctx context.Context) <-chan struct{} {
api.Post("/register", handler.LocalRegister())
api.Post("/offer", handler.LocalOffer())
api.Post("/answer", handler.LocalAnswer())
api.Post("/candidate", handler.LocalCandidate())
api.Get("/clients", handler.LocalClients())
api.Get("/ws", handler.LocalWS())
}

View File

@ -224,16 +224,19 @@ func (rc *roomController) Unregister(client *roomClient) {
rc.Broadcast(map[string]any{"type": RoomMessageTypeLeave, "time": time.Now().UnixMilli(), "body": client})
}
func (rc *roomController) Offer(id string, offer *RoomOffer, candidate *RoomCandidate) {
func (rc *roomController) Offer(id, from string, offer *RoomOffer) {
if _, ok := rc.clients[id]; !ok {
return
}
rc.clients[id].msgChan <- map[string]any{
"type": "offer",
"id": id,
"offer": offer,
"candidate": candidate,
"type": "offer",
"time": time.Now().UnixMilli(),
"data": map[string]any{
"id": id,
"from": from,
"offer": offer,
},
}
}
@ -243,8 +246,32 @@ func (rc *roomController) Answer(id string, answer *RoomOffer) {
}
rc.clients[id].msgChan <- map[string]any{
"type": "answer",
"id": id,
"answer": answer,
"type": "answer",
"time": time.Now().UnixMilli(),
"data": map[string]any{
"id": id,
"answer": answer,
},
}
}
func (rc *roomController) Candidate(id string, candidate *RoomCandidate) {
if _, ok := rc.clients[id]; !ok {
return
}
for _, client := range rc.clients {
if client.Id == id {
continue
}
client.msgChan <- map[string]any{
"type": "candidate",
"time": time.Now().UnixMilli(),
"data": map[string]any{
"id": client.Id,
"candidate": candidate,
},
}
}
}

View File

@ -61,9 +61,9 @@ func LocalWS() nf.HandlerFunc {
func LocalOffer() nf.HandlerFunc {
return func(c *nf.Ctx) error {
type Req struct {
Id string `json:"id"`
Offer *controller.RoomOffer `json:"offer"`
Candidate *controller.RoomCandidate `json:"candidate"`
Id string `json:"id"`
From string `json:"from"`
Offer *controller.RoomOffer `json:"offer"`
}
var (
@ -75,7 +75,7 @@ func LocalOffer() nf.HandlerFunc {
return c.Status(http.StatusBadRequest).JSON(map[string]string{"err": err.Error()})
}
controller.RoomController.Offer(req.Id, req.Offer, req.Candidate)
controller.RoomController.Offer(req.Id, req.From, req.Offer)
return resp.Resp200(c, req.Offer)
}
@ -102,3 +102,25 @@ func LocalAnswer() nf.HandlerFunc {
return resp.Resp200(c, req)
}
}
func LocalCandidate() nf.HandlerFunc {
return func(c *nf.Ctx) error {
type Req struct {
Id string `json:"id"`
Candidate *controller.RoomCandidate `json:"candidate"`
}
var (
err error
req = new(Req)
)
if err = c.BodyParser(req); err != nil {
return c.Status(http.StatusBadRequest).JSON(map[string]string{"err": err.Error()})
}
controller.RoomController.Candidate(req.Id, req.Candidate)
return resp.Resp200(c, req)
}
}