-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.gd
103 lines (71 loc) · 2.52 KB
/
client.gd
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
extends "ws_webrtc_client.gd"
var rtc_mp: WebRTCMultiplayer = WebRTCMultiplayer.new()
var sealed = false
func _init():
connect("connected", self, "connected")
connect("disconnected", self, "disconnected")
connect("offer_received", self, "offer_received")
connect("answer_received", self, "answer_received")
connect("candidate_received", self, "candidate_received")
connect("lobby_joined", self, "lobby_joined")
connect("lobby_sealed", self, "lobby_sealed")
connect("peer_connected", self, "peer_connected")
connect("peer_disconnected", self, "peer_disconnected")
func start(url, lobby = ""):
stop()
sealed = false
self.lobby = lobby
connect_to_url(url)
func stop():
rtc_mp.close()
close()
func _create_peer(id):
var peer: WebRTCPeerConnection = WebRTCPeerConnection.new()
peer.initialize(config)
peer.connect("session_description_created", self, "_offer_created", [id])
peer.connect("ice_candidate_created", self, "_new_ice_candidate", [id])
rtc_mp.add_peer(peer, id)
print(id, " - ", peer.get_connection_state())
var unique_id = rtc_mp.get_unique_id()
print("unique_id:", unique_id)
if id > unique_id: # Only one of the two peers can create the offer
peer.create_offer()
return peer
func _new_ice_candidate(mid_name, index_name, sdp_name, id):
send_candidate(id, mid_name, index_name, sdp_name)
func _offer_created(type, data, id):
if not rtc_mp.has_peer(id):
return
print("created", type)
rtc_mp.get_peer(id).connection.set_local_description(type, data)
if type == "offer": send_offer(id, data)
else: send_answer(id, data)
func connected(id):
print("Connected %d" % id)
rtc_mp.initialize(id, true)
func lobby_joined(lobby):
self.lobby = lobby
func lobby_sealed():
sealed = true
func disconnected():
print("Disconnected: %d: %s" % [code, reason])
if not sealed:
stop() # Unexpected disconnect
func peer_connected(id):
print("Peer connected %d" % id)
_create_peer(id)
func peer_disconnected(id):
print("Peer disconnected %d" % id)
if rtc_mp.has_peer(id): rtc_mp.remove_peer(id)
func offer_received(id, offer):
print("Got offer: %d" % id)
if rtc_mp.has_peer(id):
rtc_mp.get_peer(id).connection.set_remote_description("offer", offer)
func answer_received(id, answer):
print("Got answer: %d" % id)
if rtc_mp.has_peer(id):
rtc_mp.get_peer(id).connection.set_remote_description("answer", answer)
func candidate_received(id, mid, index, sdp):
print("Candidate received from %d (%s)" % [id, str(sdp)])
if rtc_mp.has_peer(id):
rtc_mp.get_peer(id).connection.add_ice_candidate(mid, index, sdp)