Skip to content

Instantly share code, notes, and snippets.

@odds-get-evened
Created January 13, 2022 23:31
Show Gist options
  • Save odds-get-evened/02ecc8488fcf543a62def9a24dca88be to your computer and use it in GitHub Desktop.
Save odds-get-evened/02ecc8488fcf543a62def9a24dca88be to your computer and use it in GitHub Desktop.
somewhat of a peer/bot
package org.white5moke;
import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
class Peer5 {
public Sender sender;
public Receiver receiver;
public int port;
public Peer5(int p) throws IOException {
port = p;
new Receiver(port).start();
new Sender(port).start();
}
}
class Receiver extends Thread {
public DatagramSocket socket;
public DatagramPacket packet;
public int port;
public Receiver(int p) throws SocketException {
port = p;
socket = new DatagramSocket(port);
packet = new DatagramPacket(new byte[1024], 1024);
}
@Override
public void run() {
String temp;
while(true) {
try {
socket.receive(packet);
temp = new String(packet.getData(), StandardCharsets.UTF_8);
System.out.println(String.format("this is what has been received: %s", temp));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class Sender extends Thread {
public byte[] data;
public DatagramSocket socket;
public DatagramPacket packet;
public InetAddress host;
public int port;
public Sender(int p) throws IOException {
host = InetAddress.getLocalHost();
port = p;
data = "Hello, weeps!".getBytes(StandardCharsets.UTF_8);
socket = new DatagramSocket();
socket.setBroadcast(true);
packet = new DatagramPacket(data, data.length, host, port);
}
public void run() {
for(int i=0; i<10; i++) {
System.out.println(String.format(
"the owls are not what they seem... %s",
new String(packet.getData(), StandardCharsets.UTF_8)
));
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class App {
public App(int port) throws IOException {
new Peer5(port);
/*
Node node1 = new Node(port);
Thread _node1 = new Thread(node1);
_node1.start();
*/
}
public static void main(String[] args) throws IOException {
new App(Integer.parseInt(args[0]));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment