Skip to content

Instantly share code, notes, and snippets.

@wudaown
Created March 13, 2018 03:22
Show Gist options
  • Save wudaown/73ad3bbb3d6f0b146111da048681cc25 to your computer and use it in GitHub Desktop.
Save wudaown/73ad3bbb3d6f0b146111da048681cc25 to your computer and use it in GitHub Desktop.
import java.io.IOException;
import java.net.*;
/*
Name: HENG WEILIANG
Group: SEP1
IP Address: 172.21.151.230
*/
public class Rfc865UdpClient {
public static void main(String[] args) {
// create datagram socket
DatagramSocket socket = null;
// define buffer length
// as define in rfc865, message cannot be longer than 512 char
int byteLength = 512;
try {
socket = new DatagramSocket();
} catch (SocketException e) {
System.out.println(e.getMessage());
}
try {
// define send message and convert to byte
String sendMsg = "HENG WEILIANG, SEP1, 172.21.151.230";
byte[] sendMsgByte = new byte[byteLength];
sendMsgByte = sendMsg.getBytes();
// define ip address and port for server
// server address 172.21.144.120
InetAddress serverAddress = InetAddress.getByName("hw1-a00");
int serverPort = 17;
// create packet to be send
DatagramPacket request = new DatagramPacket(sendMsgByte, sendMsgByte.length, serverAddress, serverPort);
// send packet
socket.send(request);
// define buffer to receive reply message
byte[] receiveMsgByte = new byte[byteLength];
// create packet object to receive reply message
DatagramPacket reply = new DatagramPacket(receiveMsgByte, receiveMsgByte.length);
// try to receive reply
try {
socket.receive(reply);
} catch (IOException ioEX) {
System.out.println(ioEX.getMessage());
}
// convert reply buffer to string
String replyMsg = new String(receiveMsgByte);
System.out.println(replyMsg);
// close socket and connection
socket.close();
} catch (UnknownHostException hostEx) {
System.out.println(hostEx.getMessage());
} catch (IOException ioEX) {
System.out.println(ioEX.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment