summaryrefslogtreecommitdiff
path: root/network/login_server.gd
blob: 6d878c49e2d904f492e1e82d97e019d1ee071691 (plain)
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
class_name LoginServer


signal received_packet(packet: Packet)
signal logged_in(packet: LoginServerLoginSuccessPacket)

var host: String
var port: int = 6900
var stream: PacketPeerStream = PacketPeerStream.new()
var peer: StreamPeerTCP = StreamPeerTCP.new()


@warning_ignore("shadowed_variable")
func _init(host: String, port: int = 6900) -> void:
	self.host = host
	self.port = port
	
	stream.stream_peer = peer
	peer.connect_to_host(host, port)
	peer.poll()


## Emits [signal received_packet].
func listen() -> void:
	if peer.get_status() == StreamPeerTCP.Status.STATUS_CONNECTED:
		var raw_packet: PackedByteArray = peer.get_partial_data(2)[1]
		if raw_packet.size() > 0:
			raw_packet += peer.get_data(peer.get_available_bytes())[1]
			var header = raw_packet.decode_u16(0)
			var packet_type = Constants.PacketDB[header]
			var packet = packet_type.from_bytes(raw_packet)
		
			received_packet.emit(packet)


func login(username: String, password: String):
	var login_server_login_packet = LoginServerLoginPacket.new()
	login_server_login_packet.username = username
	login_server_login_packet.password = password
	
	peer.put_data(login_server_login_packet.to_bytes())
	
	var packet = await received_packet
	if packet is LoginServerLoginSuccessPacket:
		print(inst_to_dict(packet))
		logged_in.emit(packet)