Skip to content

Commit 426d4a8

Browse files
committed
Updated to 1.3
Added connection manager Fixed broadcast not working for UDP bug, modified the ServerListeners Shortened and updated the example code
1 parent d9f8a6e commit 426d4a8

9 files changed

Lines changed: 220 additions & 151 deletions

File tree

README.md

Lines changed: 10 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,9 @@ public static void main(String[] args) throws Exception {
4545
// Wait for a few seconds
4646
Thread.sleep(3000L);
4747

48-
// Broadcast the compressed packet to all connected clients using TCP
48+
// Broadcast the compressed packet to all connected clients using TCP & UDP
4949
server.broadcast(ProtocolType.TCP, compressedPacket);
50+
server.broadcast(ProtocolType.UDP, compressedPacket);
5051

5152
// Wait for a second
5253
Thread.sleep(1000L);
@@ -67,7 +68,7 @@ public static Packet createSamplePacket() {
6768

6869
return builder
6970
.withInt(random.nextInt())
70-
.withString(generateRandomString(10))
71+
.withString("Hello, World!")
7172
.withBoolean(random.nextBoolean())
7273
.withDouble(random.nextDouble())
7374
.withLong(random.nextLong())
@@ -85,58 +86,27 @@ private static void processPacket(Packet packet) throws Exception {
8586
Packet decompressedPacket = PacketCompressor.decompress(packet, PacketCompressor.GZIP_COMPRESSOR);
8687
Packet decryptedPacket = PacketEncryptor.decrypt(decompressedPacket, secretKey);
8788
try (PacketReader reader = new PacketReader(decryptedPacket)) {
88-
int intValue = reader.readInt();
89-
String stringValue = reader.readString();
90-
boolean booleanValue = reader.readBoolean();
91-
double doubleValue = reader.readDouble();
92-
long longValue = reader.readLong();
93-
float floatValue = reader.readFloat();
94-
short shortValue = reader.readShort();
95-
byte[] bytesValue = reader.readBytes();
96-
UUID uuidValue = reader.readUUID();
97-
98-
System.out.println("Int Value: " + intValue);
99-
System.out.println("String Value: " + stringValue);
100-
System.out.println("Boolean Value: " + booleanValue);
101-
System.out.println("Double Value: " + doubleValue);
102-
System.out.println("Long Value: " + longValue);
103-
System.out.println("Float Value: " + floatValue);
104-
System.out.println("Short Value: " + shortValue);
105-
System.out.println("Bytes Value: " + Arrays.toString(bytesValue));
106-
System.out.println("UUID Value: " + uuidValue);
89+
// Read the values in the same order as they were written and use the values
10790
} catch (Exception e) {
10891
throw new RuntimeException(e);
10992
}
11093
}
11194

112-
private static String generateRandomString(int length) {
113-
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
114-
StringBuilder sb = new StringBuilder(length);
115-
Random random = new Random();
116-
117-
for (int i = 0; i < length; i++) {
118-
int index = random.nextInt(chars.length());
119-
sb.append(chars.charAt(index));
120-
}
121-
122-
return sb.toString();
123-
}
124-
12595
public static IServerListener createServerListener() {
12696
return new ServerListenerAdapter() {
12797
@Override
128-
public void onConnected(Socket socket) {
98+
public void onConnected(Connection connection) {
12999
System.out.println("SERVER >> Client connected");
130100
}
131101

132102
@Override
133-
public void onDisconnected(Socket socket) {
103+
public void onDisconnected(Connection connection) {
134104
System.out.println("SERVER >> Client disconnected");
135105
}
136106

137107
@Override
138-
public void onReceived(InetAddress address, int port, ProtocolType protocolType, Packet packet) {
139-
System.out.println("SERVER >> Data received from " + address.getHostName() + ":" + port + " using " + protocolType.name() + "(" + packet.getData().length + " bytes" + ")");
108+
public void onReceived(Connection connection, ProtocolType protocolType, Packet packet) {
109+
System.out.println("SERVER >> Data received from " + connection.getTcpSocket().getInetAddress() + ":" + (protocolType == ProtocolType.TCP ? connection.getTcpSocket().getPort() : connection.getUdpPort().get()) + " using " + protocolType.name() + "(" + packet.getData().length + " bytes" + ")");
140110
try {
141111
processPacket(packet);
142112
} catch (Exception e) {
@@ -145,8 +115,8 @@ public static IServerListener createServerListener() {
145115
}
146116

147117
@Override
148-
public void onSent(InetAddress address, int port, ProtocolType protocolType, Packet packet) {
149-
System.out.println("SERVER >> Data sent to " + address.getHostName() + ":" + port + " using " + protocolType.name() + "(" + packet.getData().length + " bytes" + ")");
118+
public void onSent(Connection connection, ProtocolType protocolType, Packet packet) {
119+
System.out.println("SERVER >> Data sent to " + connection.getTcpSocket().getInetAddress() + ":" + (protocolType == ProtocolType.TCP ? connection.getTcpSocket().getPort() : connection.getUdpPort().get()) + " using " + protocolType.name() + "(" + packet.getData().length + " bytes" + ")");
150120
}
151121
};
152122
}

pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
<groupId>xyz.synse</groupId>
88
<artifactId>PacketNet</artifactId>
9-
<version>1.2</version>
9+
<version>1.3</version>
1010

1111
<properties>
1212
<maven.compiler.source>20</maven.compiler.source>

src/main/java/xyz/synse/packetnet/Test.java

Lines changed: 11 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,11 @@
99
import xyz.synse.packetnet.common.packets.Packet;
1010
import xyz.synse.packetnet.common.packets.PacketBuilder;
1111
import xyz.synse.packetnet.common.packets.PacketReader;
12+
import xyz.synse.packetnet.server.Connection;
1213
import xyz.synse.packetnet.server.Server;
1314
import xyz.synse.packetnet.server.listeners.IServerListener;
1415
import xyz.synse.packetnet.server.listeners.ServerListenerAdapter;
1516

16-
import java.net.InetAddress;
17-
import java.net.Socket;
18-
import java.util.Arrays;
1917
import java.util.Random;
2018
import java.util.UUID;
2119

@@ -45,8 +43,9 @@ public static void main(String[] args) throws Exception {
4543
// Wait for a few seconds
4644
Thread.sleep(3000L);
4745

48-
// Broadcast the compressed packet to all connected clients using TCP
46+
// Broadcast the compressed packet to all connected clients using TCP & UDP
4947
server.broadcast(ProtocolType.TCP, compressedPacket);
48+
server.broadcast(ProtocolType.UDP, compressedPacket);
5049

5150
// Wait for a second
5251
Thread.sleep(1000L);
@@ -67,7 +66,7 @@ public static Packet createSamplePacket() {
6766

6867
return builder
6968
.withInt(random.nextInt())
70-
.withString(generateRandomString(10))
69+
.withString("Hello, World!")
7170
.withBoolean(random.nextBoolean())
7271
.withDouble(random.nextDouble())
7372
.withLong(random.nextLong())
@@ -85,58 +84,27 @@ private static void processPacket(Packet packet) throws Exception {
8584
Packet decompressedPacket = PacketCompressor.decompress(packet, PacketCompressor.GZIP_COMPRESSOR);
8685
Packet decryptedPacket = PacketEncryptor.decrypt(decompressedPacket, secretKey);
8786
try (PacketReader reader = new PacketReader(decryptedPacket)) {
88-
int intValue = reader.readInt();
89-
String stringValue = reader.readString();
90-
boolean booleanValue = reader.readBoolean();
91-
double doubleValue = reader.readDouble();
92-
long longValue = reader.readLong();
93-
float floatValue = reader.readFloat();
94-
short shortValue = reader.readShort();
95-
byte[] bytesValue = reader.readBytes();
96-
UUID uuidValue = reader.readUUID();
97-
98-
System.out.println("Int Value: " + intValue);
99-
System.out.println("String Value: " + stringValue);
100-
System.out.println("Boolean Value: " + booleanValue);
101-
System.out.println("Double Value: " + doubleValue);
102-
System.out.println("Long Value: " + longValue);
103-
System.out.println("Float Value: " + floatValue);
104-
System.out.println("Short Value: " + shortValue);
105-
System.out.println("Bytes Value: " + Arrays.toString(bytesValue));
106-
System.out.println("UUID Value: " + uuidValue);
87+
// Read the values in the same order as they were written and use the values
10788
} catch (Exception e) {
10889
throw new RuntimeException(e);
10990
}
11091
}
11192

112-
private static String generateRandomString(int length) {
113-
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
114-
StringBuilder sb = new StringBuilder(length);
115-
Random random = new Random();
116-
117-
for (int i = 0; i < length; i++) {
118-
int index = random.nextInt(chars.length());
119-
sb.append(chars.charAt(index));
120-
}
121-
122-
return sb.toString();
123-
}
124-
12593
public static IServerListener createServerListener() {
12694
return new ServerListenerAdapter() {
12795
@Override
128-
public void onConnected(Socket socket) {
96+
public void onConnected(Connection connection) {
12997
System.out.println("SERVER >> Client connected");
13098
}
13199

132100
@Override
133-
public void onDisconnected(Socket socket) {
101+
public void onDisconnected(Connection connection) {
134102
System.out.println("SERVER >> Client disconnected");
135103
}
136104

137105
@Override
138-
public void onReceived(InetAddress address, int port, ProtocolType protocolType, Packet packet) {
139-
System.out.println("SERVER >> Data received from " + address.getHostName() + ":" + port + " using " + protocolType.name() + "(" + packet.getData().length + " bytes" + ")");
106+
public void onReceived(Connection connection, ProtocolType protocolType, Packet packet) {
107+
System.out.println("SERVER >> Data received from " + connection.getTcpSocket().getInetAddress() + ":" + (protocolType == ProtocolType.TCP ? connection.getTcpSocket().getPort() : connection.getUdpPort().get()) + " using " + protocolType.name() + "(" + packet.getData().length + " bytes" + ")");
140108
try {
141109
processPacket(packet);
142110
} catch (Exception e) {
@@ -145,8 +113,8 @@ public void onReceived(InetAddress address, int port, ProtocolType protocolType,
145113
}
146114

147115
@Override
148-
public void onSent(InetAddress address, int port, ProtocolType protocolType, Packet packet) {
149-
System.out.println("SERVER >> Data sent to " + address.getHostName() + ":" + port + " using " + protocolType.name() + "(" + packet.getData().length + " bytes" + ")");
116+
public void onSent(Connection connection, ProtocolType protocolType, Packet packet) {
117+
System.out.println("SERVER >> Data sent to " + connection.getTcpSocket().getInetAddress() + ":" + (protocolType == ProtocolType.TCP ? connection.getTcpSocket().getPort() : connection.getUdpPort().get()) + " using " + protocolType.name() + "(" + packet.getData().length + " bytes" + ")");
150118
}
151119
};
152120
}

src/main/java/xyz/synse/packetnet/client/Client.java

Lines changed: 59 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import xyz.synse.packetnet.client.listeners.IClientListener;
44
import xyz.synse.packetnet.common.ProtocolType;
55
import xyz.synse.packetnet.common.packets.Packet;
6+
import xyz.synse.packetnet.common.packets.PacketBuilder;
67

78
import java.io.IOException;
89
import java.net.*;
@@ -38,23 +39,43 @@ public void connect(String serverAddress, int tcpPort, int udpPort) throws IOExc
3839
this.tcpPort = tcpPort;
3940
this.udpPort = udpPort;
4041

41-
// Init tcp
42+
// Initialize TCP connection
4243
tcpSocket = new Socket(serverAddress, tcpPort);
4344
tcpThread = new Thread(this::startTcpListener);
4445
tcpThread.start();
4546

4647
udpListenerRunning = true;
47-
// Init udp
48+
// Initialize UDP connection
4849
udpSocket = new DatagramSocket();
4950
udpThread = new Thread(this::startUdpListener);
5051
udpThread.start();
5152

53+
// Send the UDP port packet to the server
54+
sendUdpPortPacket(udpSocket.getLocalPort());
55+
5256
// Notify listeners about the connection
5357
listeners.forEach(IClientListener::onConnected);
5458
}
5559

60+
/**
61+
* Sends the UDP port packet to the server.
62+
*
63+
* @param port The local UDP port to send.
64+
* @throws IOException if an I/O error occurs while sending the packet.
65+
*/
66+
private void sendUdpPortPacket(int port) throws IOException {
67+
try (PacketBuilder packetBuilder = new PacketBuilder((short) -1000)) {
68+
packetBuilder.withInt(port);
69+
sendInternal(packetBuilder.build(), ProtocolType.TCP);
70+
} catch (Exception e) {
71+
throw new IOException("Failed sending the UDP port packet", e);
72+
}
73+
}
74+
5675
/**
5776
* Disconnects the client from the server.
77+
*
78+
* @throws IOException if an I/O error occurs during disconnection.
5879
*/
5980
public void disconnect() throws IOException {
6081
if (tcpSocket != null && !tcpSocket.isClosed()) {
@@ -110,6 +131,9 @@ public void removeListener(IClientListener listener) {
110131
this.listeners.remove(listener);
111132
}
112133

134+
/**
135+
* Starts the TCP listener thread to receive data from the server.
136+
*/
113137
private void startTcpListener() {
114138
try {
115139
byte[] buffer = new byte[bufferSize];
@@ -126,6 +150,9 @@ private void startTcpListener() {
126150
}
127151
}
128152

153+
/**
154+
* Starts the UDP listener thread to receive data from the server.
155+
*/
129156
private void startUdpListener() {
130157
byte[] buffer = new byte[bufferSize];
131158

@@ -150,31 +177,52 @@ private void startUdpListener() {
150177
*
151178
* @param packet The packet to send.
152179
* @param protocol The protocol to use (TCP or UDP).
180+
* @throws IOException if an I/O error occurs while sending the packet.
153181
*/
154182
public void send(Packet packet, ProtocolType protocol) throws IOException {
183+
sendInternal(packet, protocol);
184+
listeners.forEach(listener -> listener.onSent(protocol, packet));
185+
}
186+
187+
/**
188+
* Sends a packet to the server using the specified protocol.
189+
*
190+
* @param packet The packet to send.
191+
* @param protocol The protocol to use (TCP or UDP).
192+
* @throws IOException if an I/O error occurs while sending the packet.
193+
*/
194+
private void sendInternal(Packet packet, ProtocolType protocol) throws IOException {
155195
switch (protocol) {
156-
case TCP -> sendTcp(packet);
157-
case UDP -> sendUdp(packet);
196+
case TCP -> sendInternalTcp(packet);
197+
case UDP -> sendInternalUdp(packet);
158198
default -> System.out.println("Unsupported protocol: " + protocol);
159199
}
160200
}
161201

162-
private void sendTcp(Packet packet) throws IOException {
202+
/**
203+
* Sends a packet to the server using the TCP protocol.
204+
*
205+
* @param packet The packet to send.
206+
* @throws IOException if an I/O error occurs while sending the packet.
207+
*/
208+
private void sendInternalTcp(Packet packet) throws IOException {
163209
if (tcpSocket != null) {
164210
byte[] data = packet.toByteArray();
165211
tcpSocket.getOutputStream().write(data);
166-
167-
listeners.forEach(listener -> listener.onSent(ProtocolType.TCP, packet));
168212
}
169213
}
170214

171-
private void sendUdp(Packet packet) throws IOException {
215+
/**
216+
* Sends a packet to the server using the UDP protocol.
217+
*
218+
* @param packet The packet to send.
219+
* @throws IOException if an I/O error occurs while sending the packet.
220+
*/
221+
private void sendInternalUdp(Packet packet) throws IOException {
172222
if (udpSocket != null) {
173223
byte[] data = packet.toByteArray();
174224
DatagramPacket datagramPacket = new DatagramPacket(data, data.length, serverAddress, udpPort);
175225
udpSocket.send(datagramPacket);
176-
177-
listeners.forEach(listener -> listener.onSent(ProtocolType.UDP, packet));
178226
}
179227
}
180228

@@ -204,4 +252,4 @@ public int getUdpPort() {
204252
public InetAddress getServerAddress() {
205253
return serverAddress;
206254
}
207-
}
255+
}

src/main/java/xyz/synse/packetnet/client/listeners/IClientListener.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package xyz.synse.packetnet.client.listeners;
22

3-
import xyz.synse.packetnet.client.Client;
43
import xyz.synse.packetnet.common.ProtocolType;
54
import xyz.synse.packetnet.common.packets.Packet;
65

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package xyz.synse.packetnet.server;
2+
3+
import java.net.Socket;
4+
import java.util.Optional;
5+
6+
public class Connection {
7+
private final Socket tcpSocket;
8+
private Optional<Integer> udpPort;
9+
10+
public Connection(Socket tcpSocket) {
11+
this.tcpSocket = tcpSocket;
12+
this.udpPort = Optional.empty();
13+
}
14+
15+
public Connection(Socket tcpSocket, int udpPort) {
16+
this.tcpSocket = tcpSocket;
17+
this.udpPort = Optional.of(udpPort);
18+
}
19+
20+
public Socket getTcpSocket() {
21+
return tcpSocket;
22+
}
23+
24+
public Optional<Integer> getUdpPort() {
25+
return udpPort;
26+
}
27+
28+
public void setUdpPort(Optional<Integer> udpPort) {
29+
this.udpPort = udpPort;
30+
}
31+
}

0 commit comments

Comments
 (0)