Skip to content

Instantly share code, notes, and snippets.

@BinRoot
Created October 2, 2012 22:08
Show Gist options
  • Save BinRoot/3823629 to your computer and use it in GitHub Desktop.
Save BinRoot/3823629 to your computer and use it in GitHub Desktop.
MyServer.java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class MyServer {
public static void main(String [] args) {
try {
DatagramSocket serverSocket = new DatagramSocket(6789);
byte[] input = new byte[1024];
System.out.println("Starting to listen on port 6789...");
while(true) {
DatagramPacket receivePacket = new DatagramPacket(input, input.length);
serverSocket.receive(receivePacket);
String msg = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String ipStr = IPAddress.toString() + ":" + port;
System.out.println("FROM " + ipStr);
System.out.println("RECEIVED: " + msg);
// for(int i=0; i<input.length; i++) {
// System.out.printf( "%02X" + " ", receivePacket.getData()[i]);
// if((i+1) % 4 == 0) {
// System.out.println();
// }
// }
}
} catch (SocketException e) {
System.err.println("SocketException: "+e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("IoException: "+e.getMessage());
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment