Created
December 28, 2022 17:11
-
-
Save devdilson/7299c13247cb699eb54608bf245e4183 to your computer and use it in GitHub Desktop.
Generated by GPT3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.net.InetSocketAddress; | |
import java.nio.ByteBuffer; | |
import java.nio.channels.SelectionKey; | |
import java.nio.channels.Selector; | |
import java.nio.channels.ServerSocketChannel; | |
import java.nio.channels.SocketChannel; | |
import java.util.Iterator; | |
import java.util.Queue; | |
import java.util.concurrent.ConcurrentLinkedQueue; | |
public class PacketReceiver { | |
private static final int BUFFER_SIZE = 1024; | |
private static final int PORT = 12345; | |
private final Queue<ByteBuffer> processingQueue = new ConcurrentLinkedQueue<>(); | |
public void start() throws IOException { | |
Selector selector = Selector.open(); | |
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); | |
serverSocketChannel.configureBlocking(false); | |
serverSocketChannel.bind(new InetSocketAddress(PORT)); | |
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); | |
while (true) { | |
selector.select(); | |
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); | |
while (iterator.hasNext()) { | |
SelectionKey key = iterator.next(); | |
if (key.isAcceptable()) { | |
SocketChannel clientSocketChannel = serverSocketChannel.accept(); | |
clientSocketChannel.configureBlocking(false); | |
clientSocketChannel.register(selector, SelectionKey.OP_READ); | |
} else if (key.isReadable()) { | |
SocketChannel clientSocketChannel = (SocketChannel) key.channel(); | |
ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); | |
clientSocketChannel.read(buffer); | |
buffer.flip(); | |
byte[] decryptedPacket = decrypt(buffer.array()); | |
processingQueue.add(ByteBuffer.wrap(decryptedPacket)); | |
} | |
iterator.remove(); | |
} | |
processPackets(); | |
} | |
} | |
private void processPackets() { | |
ByteBuffer buffer; | |
while ((buffer = processingQueue.poll()) != null) { | |
printPacket(buffer); | |
} | |
} | |
private void printPacket(ByteBuffer buffer) { | |
while (buffer.hasRemaining()) { | |
System.out.printf("%02x", buffer.get()); | |
} | |
System.out.println(); | |
} | |
private byte[] decrypt(byte[] packet) { | |
// Decrypt the packet here using the appropriate protocol | |
return packet; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment