Created
November 9, 2021 17:57
-
-
Save odds-get-evened/18c3da86be9e0785ff8217dc3cecc86c to your computer and use it in GitHub Desktop.
P2P node practice
This file contains 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 org.white5moke.util.ByteSplitter; | |
import java.io.IOException; | |
import java.net.*; | |
import java.nio.charset.StandardCharsets; | |
class Cj5xNode extends Thread { | |
private DatagramSocket socketIn; | |
private DatagramSocket socketOut; | |
private boolean isRunning = false; | |
private byte[] buffer = new byte[64]; | |
private static final int PORT_IN = 6881; | |
private static final int PORT_OUT = 6882; | |
private InetAddress address; | |
public Cj5xNode() throws SocketException, UnknownHostException { | |
address = InetAddress.getLocalHost(); | |
socketIn = new DatagramSocket(PORT_IN); | |
socketOut = new DatagramSocket(PORT_OUT); | |
} | |
@Override | |
public void run() { | |
isRunning = true; | |
try { | |
rx(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
private void rx() throws IOException { | |
while(isRunning) { | |
DatagramPacket packet = new DatagramPacket(buffer, buffer.length); | |
socketIn.receive(packet); | |
InetAddress txAddress = packet.getAddress(); | |
int txPort = packet.getPort(); | |
packet = new DatagramPacket(buffer, buffer.length, txAddress, txPort); | |
/*String txMessage = new String(packet.getData(), 0, packet.getLength()); | |
socketIn.send(packet);*/ | |
} | |
socketIn.close(); | |
} | |
public void tx(String message) { | |
while(isRunning) { | |
broadcast(message.getBytes(StandardCharsets.UTF_8)); | |
} | |
} | |
private void broadcast(byte[] data) { | |
ByteSplitter bh = new ByteSplitter(data, 64); | |
bh.getStack().forEach(b -> { | |
DatagramPacket packet = new DatagramPacket(b, b.length, socketOut.getInetAddress(), socketOut.getPort()); | |
try { | |
socketOut.send(packet); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
}); | |
} | |
} | |
class ScratchGrams { | |
public static void main(String[] args) throws SocketException, UnknownHostException { | |
Cj5xNode node1 = new Cj5xNode(); | |
Thread _node1 = new Thread(node1); | |
_node1.start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment