-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.go
316 lines (250 loc) · 8.96 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package main
import (
"encoding/json"
"fmt"
"net"
"net/http"
"strconv"
"sync"
"time"
//"reflect"
//"encoding/binary"
"github.com/gorilla/websocket"
"github.com/pion/webrtc/v3"
"github.com/wawesomeNOGUI/webrtcGameTemplate/signal"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
var api *webrtc.API
func echo(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println("Upgrade: ", err)
return
}
defer c.Close()
fmt.Println("User connected from: ", c.RemoteAddr())
//===========This Player's Variables===================
var playerTag string
//===========WEBRTC====================================
// Create a new RTCPeerConnection
peerConnection, err := api.NewPeerConnection(webrtc.Configuration{})
if err != nil {
panic(err)
}
//Setup dataChannel to act like UDP with ordered messages (no retransmits)
//with the DataChannelInit struct
var udpPls webrtc.DataChannelInit
var retransmits uint16 = 0
//DataChannel will drop any messages older than
//the most recent one received if ordered = true && retransmits = 0
//This is nice so we can always assume client
//side that the message received from the server
//is the most recent update, and not have to
//implement logic for handling old messages
var ordered = true
udpPls.Ordered = &ordered
udpPls.MaxRetransmits = &retransmits
// Create a datachannel with label 'UDP' and options udpPls
dataChannel, err := peerConnection.CreateDataChannel("UDP", &udpPls)
if err != nil {
panic(err)
}
//Create a reliable datachannel with label "TCP" for all other communications
reliableChannel, err := peerConnection.CreateDataChannel("TCP", nil)
if err != nil {
panic(err)
}
// Set the handler for ICE connection state
// This will notify you when the peer has connected/disconnected
peerConnection.OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) {
fmt.Printf("ICE Connection State has changed: %s\n", connectionState.String())
//3 = ICEConnectionStateConnected
if connectionState == 3 {
//Store a new x and y for this player
NumberOfPlayers++
playerTag = strconv.Itoa(NumberOfPlayers)
fmt.Println(playerTag)
//Store a slice for player x, y, and other data
//Initially we'll just have starting x and y values
Updates.Store(playerTag, []int{0, 0})
} else if connectionState == 5 || connectionState == 6 || connectionState == 7 {
Updates.Delete(playerTag)
fmt.Println("Deleted Player")
err := peerConnection.Close() //deletes all references to this peerconnection in mem and same for ICE agent (ICE agent releases the "closed" status)
if err != nil { //https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close
fmt.Println(err)
}
}
})
//====================No retransmits, ordered dataChannel=======================
// Register channel opening handling
dataChannel.OnOpen(func() {
for {
time.Sleep(time.Millisecond * 50) //50 milliseconds = 20 updates per second
//20 milliseconds = ~60 updates per second
//fmt.Println(UpdatesString)
// Send the message as text so we can JSON.parse in javascript
sendErr := dataChannel.SendText(UpdatesString)
if sendErr != nil {
fmt.Println("data send err", sendErr)
break
}
}
})
// Register text message handling
dataChannel.OnMessage(func(msg webrtc.DataChannelMessage) {
fmt.Printf("Message from DataChannel '%s': '%s'\n", dataChannel.Label(), string(msg.Data))
})
//==============================================================================
//=========================Reliable DataChannel=================================
// Register channel opening handling
reliableChannel.OnOpen(func() {
//Send Client their playerTag so they know who they are in the Updates Array
sendErr := reliableChannel.SendText(playerTag)
if sendErr != nil {
panic(err)
}
})
// Register message handling (Data all served as a bytes slice []byte)
// for user controls
reliableChannel.OnMessage(func(msg webrtc.DataChannelMessage) {
//fmt.Printf("Message from DataChannel '%s': '%s'\n", reliableChannel.Label(), string(msg.Data))
//fmt.Println(msg.Data)
if msg.Data[0] == 88 { //88 = "X"
x, err := strconv.Atoi(string(msg.Data[1:]))
if err != nil {
fmt.Println(err)
}
playerSlice, ok := Updates.Load(playerTag)
if ok == false {
fmt.Println("Uh oh")
}
playerSlice.([]int)[0] = x
Updates.Store(playerTag, playerSlice)
} else if msg.Data[0] == 89 { //89 = "Y"
y, err := strconv.Atoi(string(msg.Data[1:]))
if err != nil {
fmt.Println(err)
}
playerSlice, ok := Updates.Load(playerTag)
if ok == false {
fmt.Println("Uh oh")
}
playerSlice.([]int)[1] = y
Updates.Store(playerTag, playerSlice)
}
})
//==============================================================================
// Create an offer to send to the browser
offer, err := peerConnection.CreateOffer(nil)
if err != nil {
panic(err)
}
// Create channel that is blocked until ICE Gathering is complete
gatherComplete := webrtc.GatheringCompletePromise(peerConnection)
// Sets the LocalDescription, and starts our UDP listeners
err = peerConnection.SetLocalDescription(offer)
if err != nil {
panic(err)
}
// Block until ICE Gathering is complete, disabling trickle ICE
// we do this because we only can exchange one signaling message
// in a production application you should exchange ICE Candidates via OnICECandidate
<-gatherComplete
fmt.Println(*peerConnection.LocalDescription())
//Send the SDP with the final ICE candidate to the browser as our offer
err = c.WriteMessage(1, []byte(signal.Encode(*peerConnection.LocalDescription()))) //write message back to browser, 1 means message in byte format?
if err != nil {
fmt.Println("write:", err)
}
//Wait for the browser to send an answer (its SDP)
msgType, message, err2 := c.ReadMessage() //ReadMessage blocks until message received
if err2 != nil {
fmt.Println("read:", err)
}
answer := webrtc.SessionDescription{}
signal.Decode(string(message), &answer) //set answer to the decoded SDP
fmt.Println(answer, msgType)
// Set the remote SessionDescription
err = peerConnection.SetRemoteDescription(answer)
if err != nil {
panic(err)
}
//=====================Trickle ICE==============================================
//Make a new struct to use for trickle ICE candidates
var trickleCandidate webrtc.ICECandidateInit
var leftBracket uint8 = 123 //123 = ascii value of "{"
for {
_, message, err2 := c.ReadMessage() //ReadMessage blocks until message received
if err2 != nil {
fmt.Println("read:", err)
}
//If staement to make sure we aren't adding websocket error messages to ICE
if message[0] == leftBracket {
//Take []byte and turn it into a struct of type webrtc.ICECandidateInit
//(declared above as trickleCandidate)
err := json.Unmarshal(message, &trickleCandidate)
if err != nil {
fmt.Println("errorUnmarshal:", err)
}
fmt.Println(trickleCandidate)
err = peerConnection.AddICECandidate(trickleCandidate)
if err != nil {
fmt.Println("errorAddICE:", err)
}
}
}
}
//We'll have this marshalling function here so the multiple gorutines for each
//player will not be inefficient by all trying to marshall the same thing
func getSyncMapReadyForSending(m *sync.Map) {
for {
time.Sleep(time.Millisecond)
tmpMap := make(map[string][]int)
m.Range(func(k, v interface{}) bool {
tmpMap[k.(string)] = v.([]int)
return true
})
jsonTemp, err := json.Marshal(tmpMap)
if err != nil {
panic(err)
}
UpdatesString = string(jsonTemp)
}
}
//Updates Map
var Updates sync.Map
var UpdatesString string
var NumberOfPlayers int
func main() {
go getSyncMapReadyForSending(&Updates)
// Listen on UDP Port 80, will be used for all WebRTC traffic
udpListener, err := net.ListenUDP("udp", &net.UDPAddr{
IP: net.IP{0, 0, 0, 0},
Port: 80,
})
if err != nil {
panic(err)
}
fmt.Printf("Listening for WebRTC traffic at %s\n", udpListener.LocalAddr())
// Create a SettingEngine, this allows non-standard WebRTC behavior
settingEngine := webrtc.SettingEngine{}
//Our Public Candidate is declared here cause were not using a STUN server for discovery
//and just hardcoding the open port, and port forwarding webrtc traffic on the router
settingEngine.SetNAT1To1IPs([]string{}, webrtc.ICECandidateTypeHost)
// Configure our SettingEngine to use our UDPMux. By default a PeerConnection has
// no global state. The API+SettingEngine allows the user to share state between them.
// In this case we are sharing our listening port across many.
settingEngine.SetICEUDPMux(webrtc.NewICEUDPMux(nil, udpListener))
// Create a new API using our SettingEngine
api = webrtc.NewAPI(webrtc.WithSettingEngine(settingEngine))
fileServer := http.FileServer(http.Dir("./public"))
http.HandleFunc("/echo", echo) //this request comes from webrtc.html
http.Handle("/", fileServer)
err = http.ListenAndServe(":80", nil) //Http server blocks
if err != nil {
panic(err)
}
}