blob: bfa53d734c600139d41cae69f03e189c7c4fe78f (
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
79
80
81
82
83
84
85
|
package cuchaz.enigma.network;
import cuchaz.enigma.gui.GuiController;
import cuchaz.enigma.network.packet.LoginC2SPacket;
import cuchaz.enigma.network.packet.Packet;
import cuchaz.enigma.network.packet.PacketRegistry;
import javax.swing.SwingUtilities;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
public class EnigmaClient {
private final GuiController controller;
private final String ip;
private final int port;
private Socket socket;
private DataOutput output;
public EnigmaClient(GuiController 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<GuiController> 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());
}
}
}
|