Clean old session

This commit is contained in:
giongto35 2019-04-14 12:54:58 +08:00
parent e96b2a4072
commit 45f634c2f0
3 changed files with 39 additions and 16 deletions

19
main.go
View file

@ -57,7 +57,7 @@ type Room struct {
director *ui.Director
}
var rooms map[string]*Room
var rooms = map[string]*Room{}
func main() {
fmt.Println("Usage: ./game [debug]")
@ -132,8 +132,24 @@ func isRoomRunning(roomID string) bool {
return false
}
// startSession cleans all of the dependencies of old game to current webRTC session
func cleanSession(webrtc *webrtc.WebRTC) {
roomID := webrtc.RoomID
if !isRoomRunning(roomID) {
return
}
for id, session := range rooms[roomID].rtcSessions {
if session == webrtc {
rooms[roomID].rtcSessions = append(rooms[roomID].rtcSessions[:id], rooms[roomID].rtcSessions[id+1:]...)
break
}
}
}
// startSession handles one session call
func startSession(webRTC *webrtc.WebRTC, gameName string, roomID string, playerIndex int) string {
cleanSession(webRTC)
// If the roomID is empty,
// or the roomID doesn't have any running sessions (room was closed)
// we spawn a new room
@ -143,6 +159,7 @@ func startSession(webRTC *webrtc.WebRTC, gameName string, roomID string, playerI
// TODO: Might have race condition
rooms[roomID].rtcSessions = append(rooms[roomID].rtcSessions, webRTC)
webRTC.AttachRoomID(roomID)
faninInput(rooms[roomID].inputChannel, webRTC, playerIndex)
return roomID

View file

@ -58,6 +58,20 @@ function startWebRTC() {
// webrtc
pc = new RTCPeerConnection({iceServers: [{urls: 'stun:stun.l.google.com:19302'}]})
// input channel
inputChannel = pc.createDataChannel('foo')
inputChannel.onclose = () => {
log('inputChannel has closed');
}
inputChannel.onopen = () => {
log('inputChannel has opened');
}
inputChannel.onmessage = e => {
log(`Message from DataChannel '${inputChannel.label}' payload '${e.data}'`);
}
pc.oniceconnectionstatechange = e => {
log(`iceConnectionState: ${pc.iceConnectionState}`);
@ -99,20 +113,6 @@ function startWebRTC() {
pc.setLocalDescription(d).catch(log);
})
// input channel
inputChannel = pc.createDataChannel('foo')
inputChannel.onclose = () => {
log('inputChannel has closed');
}
inputChannel.onopen = () => {
log('inputChannel has opened');
}
inputChannel.onmessage = e => {
log(`Message from DataChannel '${inputChannel.label}' payload '${e.data}'`);
}
}
function startGame() {

View file

@ -6,8 +6,8 @@ import (
"compress/gzip"
"encoding/base64"
"encoding/json"
"log"
"io/ioutil"
"log"
"math/rand"
"time"
@ -107,6 +107,8 @@ type WebRTC struct {
// for yuvI420 image
ImageChannel chan []byte
InputChannel chan int
RoomID string
}
// StartClient start webrtc
@ -204,6 +206,10 @@ func (w *WebRTC) StartClient(remoteSession string, width, height int) (string, e
return localSession, nil
}
func (w *WebRTC) AttachRoomID(roomID string) {
w.RoomID = roomID
}
// TODO: Take a look at this
func (w *WebRTC) AddCandidate(candidate webrtc.ICECandidateInit) {
err := w.connection.AddICECandidate(candidate)