summaryrefslogtreecommitdiff
path: root/enigma-server/src/main/java/cuchaz/enigma/network/EnigmaClient.java
blob: 71bd011c36f2fbccca34c8a2bb496c2053371d3f (plain) (blame)
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
package cuchaz.enigma.network;

import cuchaz.enigma.network.packet.Packet;
import cuchaz.enigma.network.packet.PacketRegistry;

import javax.swing.*;
import java.io.*;
import java.net.Socket;
import java.net.SocketException;

public class EnigmaClient {

	private final ClientPacketHandler controller;

	private final String ip;
	private final int port;
	private Socket socket;
	private DataOutput output;

	public EnigmaClient(ClientPacketHandler controller, String ip, int port) {
		this.controller = controller;
		this.ip = ip;
		this.port = port;
	}

	public void connect() throws IOException {
		socket = new Socket(ip, port);
		output = new DataOutputStream(socket.getOutputStream());
		Thread thread = new Thread(() -> {
			try {
				DataInput input = new DataInputStream(socket.getInputStream());
				while (true) {
					int packetId;
					try {
						packetId = input.readUnsignedByte();
					} catch (EOFException | SocketException e) {
						break;
					}
					Packet<ClientPacketHandler> packet = PacketRegistry.createS2CPacket(packetId);
					if (packet == null) {
						throw new IOException("Received invalid packet id " + packetId);
					}
					packet.read(input);
					SwingUtilities.invokeLater(() -> packet.handle(controller));
				}
			} catch (IOException e) {
				controller.disconnectIfConnected(e.toString());
				return;
			}
			controller.disconnectIfConnected("Disconnected");
		});
		thread.setName("Client I/O thread");
		thread.setDaemon(true);
		thread.start();
	}

	public synchronized void disconnect() {
		if (socket != null && !socket.isClosed()) {
			try {
				socket.close();
			} catch (IOException e1) {
				System.err.println("Failed to close socket");
				e1.printStackTrace();
			}
		}
	}


	public void sendPacket(Packet<ServerPacketHandler> packet) {
		try {
			output.writeByte(PacketRegistry.getC2SId(packet));
			packet.write(output);
		} catch (IOException e) {
			controller.disconnectIfConnected(e.toString());
		}
	}

}