WebRTC.gd 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. extends Node
  2. var peer = WebRTCPeerConnection.new()
  3. var wsclient
  4. var username
  5. # Create negotiated data channel
  6. var channel = peer.create_data_channel("position", {"negotiated": true, "id": 1})
  7. func _ready():
  8. # Connect all functions
  9. peer.connect("ice_candidate_created", self, "_on_ice_candidate")
  10. peer.connect("session_description_created", self, "_on_session")
  11. # Register to the local signaling server (see below for the implementation)
  12. wsclient = find_node("WSClient")
  13. wsclient.connect("ws_login_in", self, "on_login_in")
  14. wsclient.connect("ws_candidate_in", self, "on_candidate_in")
  15. wsclient.connect("ws_session_in", self, "on_session_in")
  16. wsclient.login()
  17. peer.create_offer()
  18. breakpoint
  19. func _on_ice_candidate(mid, index, sdp):
  20. # Send the ICE candidate to the other peer via signaling server
  21. var data = {"mtype": "candidate", "payload": {"mid": mid, "index": index, "sdp": sdp}}
  22. emit_signal("ws_out", data)
  23. func _on_session(type, sdp):
  24. # Send the session to other peer via signaling server
  25. var data = {"mtype": "session", "payload": {"type": type, "sdp": sdp}}
  26. emit_signal("ws_out", data)
  27. # Set generated description as local
  28. peer.set_local_description(type, sdp)
  29. func _process(delta):
  30. # Always poll the connection frequently
  31. peer.poll()
  32. if channel.get_ready_state() == WebRTCDataChannel.STATE_OPEN:
  33. while channel.get_available_packet_count() > 0:
  34. print(get_path(), " received: ", channel.get_packet().get_string_from_utf8())
  35. func send_message(message):
  36. channel.put_packet(message.to_utf8())
  37. func on_session_in(type, sdp):
  38. peer.set_remote_description(type, sdp)
  39. func on_candidate_in(mid, index, sdp):
  40. peer.add_ice_candidate(mid, index, sdp)
  41. func on_ws_login_in(msg):
  42. print(msg)