Created
March 13, 2018 03:22
-
-
Save wudaown/fa0b02c0938558796ae53cfd541b0816 to your computer and use it in GitHub Desktop.
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 java.io.IOException; | |
import java.net.*; | |
public class Rfc865UdpServer { | |
public static void main(String[] args) { | |
// | |
// open udp socket at well know port | |
// | |
DatagramSocket socket = null; | |
try { | |
socket = new DatagramSocket(17); | |
} catch (SocketException e) { | |
System.out.println(e.getMessage()); | |
} | |
int byteLength = 512; | |
byte[] receiveData = new byte[byteLength]; | |
while (true) { | |
try { | |
// | |
// listen for UDP request from client | |
// | |
System.out.println("Waiting to receive request"); | |
DatagramPacket request = new DatagramPacket(receiveData, receiveData.length); | |
try { | |
socket.receive(request); | |
} catch (NullPointerException nullEx) { | |
nullEx.getMessage(); | |
} | |
String receiveMsg = new String(receiveData); | |
System.out.println(receiveMsg); | |
// | |
// Send UDP reply to client | |
// | |
InetAddress clientAddress = request.getAddress(); | |
int clientPort = request.getPort(); | |
String msg = "Message received! waiting for another message"; | |
byte[] replyMsg = new byte[512]; | |
replyMsg = msg.getBytes(); | |
DatagramPacket reply = new DatagramPacket(replyMsg,replyMsg.length,clientAddress,clientPort); | |
socket.send(reply); | |
System.out.println("Reply send"); | |
} catch (IOException e) { | |
e.getMessage(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment