|
|
|
@ -1,8 +1,9 @@
|
|
|
|
|
extends Node
|
|
|
|
|
|
|
|
|
|
const PORT = 8080
|
|
|
|
|
var _server = WebSocketServer.new()
|
|
|
|
|
var peers = [] # everyone currently connected
|
|
|
|
|
const PORT = 8080
|
|
|
|
|
var _server = WebSocketServer.new()
|
|
|
|
|
var IDs = {}
|
|
|
|
|
var peers = []
|
|
|
|
|
|
|
|
|
|
func _ready():
|
|
|
|
|
_server.connect('client_connected', self, "_connected")
|
|
|
|
@ -17,10 +18,11 @@ func _ready():
|
|
|
|
|
print_debug("server started")
|
|
|
|
|
|
|
|
|
|
func _connected(id, protocol):
|
|
|
|
|
print_debug("Client %d connected with protocol: %s"
|
|
|
|
|
% [id, protocol])
|
|
|
|
|
print_debug("Client %d connected with protocol: %s" % [id, protocol])
|
|
|
|
|
_server.get_peer(id).put_packet(JSON.print(
|
|
|
|
|
{'type': 'test', 'message': "test packet from server"}).to_utf8())
|
|
|
|
|
{'type': 'test', 'message': "Server test packet"}).to_utf8()
|
|
|
|
|
)
|
|
|
|
|
peers.append(id)
|
|
|
|
|
|
|
|
|
|
func _close_request(id, code, reason):
|
|
|
|
|
print_debug("Client %d disconnecting with code: %d, reason: %s"
|
|
|
|
@ -29,6 +31,13 @@ func _close_request(id, code, reason):
|
|
|
|
|
func _disconnected(id, was_clean = false):
|
|
|
|
|
print_debug("Client %d disconnected, clean: %s"
|
|
|
|
|
% [id, str(was_clean)])
|
|
|
|
|
var user = IDs[id]
|
|
|
|
|
peers.erase(id)
|
|
|
|
|
for p in peers:
|
|
|
|
|
_server.get_peer(p).put_packet(JSON.print(
|
|
|
|
|
{'type': "server_message", "message": user
|
|
|
|
|
+ "(#" + str(id) + ") left the chat."}
|
|
|
|
|
).to_utf8())
|
|
|
|
|
|
|
|
|
|
func _on_data_received(id):
|
|
|
|
|
|
|
|
|
@ -39,7 +48,18 @@ func _on_data_received(id):
|
|
|
|
|
push_error("%s is not a dictionary" % [packet])
|
|
|
|
|
get_tree().quit()
|
|
|
|
|
|
|
|
|
|
print_debug("Got data from client %d: %s" % [id, packet])
|
|
|
|
|
print_debug("Got data from client %d: %s ... echoing" % [id, packet])
|
|
|
|
|
if packet['type'] == "user_joined":
|
|
|
|
|
IDs[id] = packet['name']
|
|
|
|
|
for p in peers:
|
|
|
|
|
_server.get_peer(p).put_packet(
|
|
|
|
|
JSON.print(
|
|
|
|
|
{'type': "server_message", "message": packet['name']
|
|
|
|
|
+ "(#" + str(id) + ") joined the chat."}
|
|
|
|
|
).to_utf8())
|
|
|
|
|
elif packet['type'] == "chat_message" or packet['type'] == "server_message":
|
|
|
|
|
for p in peers:
|
|
|
|
|
_server.get_peer(p).put_packet(JSON.print(packet).to_utf8())
|
|
|
|
|
|
|
|
|
|
func _process(_delta):
|
|
|
|
|
_server.poll()
|
|
|
|
|