You are on page 1of 9

LAB 2: Developing UDP applications

Learning Outcomes
This Labsheet encompasses of activities which is 3A, 3B, and 3C.
By the end of this laboratory session, you should be able to:
1. Developing datagrampacket and datagramsocket
2. Developing send and receive file program.
3. Developing multicast socket.

Hardware/ Software : Eclipse IDE

Activity 2A(CLO :2)


Activity Outcome: create datagram packet and socket
Step 1: Open Eclipse and type the code in Figure 2a(1). The source code is the console
application using UDP protocol to send data to another computer.
Step 2: The localhost in the source code need to be changed with the IP provided by
the instructor. Your message will be displayed to the instructors monitor.

import java.io.*;
import java.net.*;
public class MySend
{ public static void main(String [] asv) throws Exception
{
// create a DatagramSocket object
DatagramSocket ds = new DatagramSocket (2021);
// determines the IP address of a host, given the hosts name
InetAddress inet = InetAddress.getByName("localhost");
for (;;)
{
// create a BufferedReader object which does input from the keyboard
BufferedReader bf=new BufferedReader(new InputStreamReader (System.in));
System.out.print("Enter Message: ");
// method readLine() is part of the BufferedReader object
// method readLine() reads a line of character data from the keyboard
String msg = bf.readLine();
// create a DatagramPacket object for the incoming datagrams
DatagramPacket dp = new DatagramPacket(buf, buf.length, inet, 2020);
// send the datagram message
ds.send(dp);
// converted to byte in order to send
byte [ ] buf = msg.getBytes();
System.out.println("Message has been sent");
}
}
}

Figure 2a(1)
Step 3: Save, compile and run the program.
Step 4: Open Eclipse and type the code in Figure 2a(2). The program in Figure 2a(1)
and 3a(2) are use to interact with 2 applications in local computer.
Step 5: The localhost in the Figure 3a(1) need to be changed to your partners IP
address.

import java.net.*;

public class MyReceive


{
public static void main(String [] asv) throws Exception
{
// create a DatagramSocket object
DatagramSocket ds = new DatagramSocket (2020);

while(true)
{
// create a buffer for incoming datagrams
byte [] buf = new byte[2000];

// create a DatagramPacket object for the incoming datagrams


DatagramPacket dp = new DatagramPacket(buf, buf.length);
// accept an incoming datagram
ds.receive(dp);

// retrive the data from the buffer


String msg = new String(buf);

// accept the senders address and host name from the packet
/* method trim() return a copy of the string, with leading and trailing whitespace
omitted */
System.out.println(dp.getAddress().getHostName()+" :"+msg.trim());
}
}
}

Figure 2a(2)

Step 3: Save and compile the program. You will run the program in Figure 3a(1) and
your partners will run the program in Figure 3a(2). Your message will be
displayed to your partners monitor.
The Expected Output:

Figure 2a(3): Sender (your's computer)

Figure 2a(4): Receiver (your partner's computer)


Activity 2B
Activity Outcome: create send and receive file program
Step 1: Open Eclipse and type the code in Figure 2b(1). The source code AppsA.java
is the console application using UDP protocol to send file to another computer.
import java.io.*;
import java.net.*;

public class AppsA {


private DatagramSocket socket = null;
private FileEvent event = null;
private String sourceFilePath = "C:/KAMA/SESI JUN 2014/FN513/recv.jpg";
private String destinationPath = "C:/KAMA/SESI JUN 2014/FN513/eclipse/";
private String hostName = "localHost";

public AppsA(){ }
public void createConnection() {
try {
socket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName(hostName);
byte[] incomingData = new byte[9999];
event = getFileEvent();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(outputStream);
os.writeObject(event);
byte[] data = outputStream.toByteArray();
DatagramPacket sendPacket = new DatagramPacket(data, data.length, IPAddress, 9876);
socket.send(sendPacket);
System.out.println("File sent from AppsA");
DatagramPacket incomingPacket = new DatagramPacket(incomingData,
incomingData.length);
socket.receive(incomingPacket);
String response = new String(incomingPacket.getData());
System.out.println("Response from AppsB:" + response);
Thread.sleep(2000);
System.exit(0);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public FileEvent getFileEvent() {
FileEvent fileEvent = new FileEvent();
String fileName = sourceFilePath.substring(sourceFilePath.lastIndexOf("/") + 1,
sourceFilePath.length());
String path = sourceFilePath.substring(0, sourceFilePath.lastIndexOf("/") + 1);
fileEvent.setDestinationDirectory(destinationPath);
fileEvent.setFilename(fileName);
fileEvent.setSourceDirectory(sourceFilePath);
File file = new File(sourceFilePath);
if (file.isFile()) {
try {
DataInputStream diStream = new DataInputStream(new FileInputStream(file));
long len = (int) file.length();
byte[] fileBytes = new byte[(int) len];
int read = 0;
int numRead = 0;
while (read < fileBytes.length && (numRead = diStream.read(fileBytes, read,
fileBytes.length - read)) >= 0) {
read = read + numRead;
} fileEvent.setFileSize(len);
fileEvent.setFileData(fileBytes);
fileEvent.setStatus("Success");
} catch (Exception e) {
e.printStackTrace();
fileEvent.setStatus("Error");
}
} else {
System.out.println("path specified is not pointing to a file");
fileEvent.setStatus("Error");
}
return fileEvent;
}
public static void main(String[] args) {
AppsA app = new AppsA();
app.createConnection();
}
}

Figure 2b(1) send file

Step 2: The address of sourceFilePath (the place that you save the .jpeg file) and
destinationPath will regarding to the address of your pc.
Step 3: Save the file and continue with the next coding.
Step 4 : Open Eclipse and type the code in Figure 2b(2). The source code AppsB.java
is the console application using UDP protocol to receive file from AppsA.java

import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class AppsB {


private DatagramSocket socket = null;
private FileEvent fileEvent = null;

public AppsB() {}

public void createAndListenSocket() {


try {
socket = new DatagramSocket(9876);
byte[] incomingData = new byte[1024 * 1000 * 50];
while (true) {
DatagramPacket incomingPacket = new DatagramPacket(incomingData,
incomingData.length);
socket.receive(incomingPacket);
byte[] data = incomingPacket.getData();
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
fileEvent = (FileEvent) is.readObject();
if (fileEvent.getStatus().equalsIgnoreCase("Error")) {
System.out.println("Some issue happened while packing the data @ client side");
System.exit(0);
}
createAndWriteFile(); // writing the file to hard disk
InetAddress IPAddress = incomingPacket.getAddress();
int port = incomingPacket.getPort();
String reply = "Thank you for the message";
byte[] replyBytea = reply.getBytes();
DatagramPacket replyPacket =new DatagramPacket(replyBytea, replyBytea.length,
IPAddress, port);
socket.send(replyPacket);
Thread.sleep(3000);
System.exit(0);
}

} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void createAndWriteFile() {
String outputFile = fileEvent.getDestinationDirectory() + fileEvent.getFilename();
if (!new File(fileEvent.getDestinationDirectory()).exists()) {
new File(fileEvent.getDestinationDirectory()).mkdirs();
}
File dstFile = new File(outputFile);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(dstFile);
fileOutputStream.write(fileEvent.getFileData());
fileOutputStream.flush();
fileOutputStream.close();
System.out.println("Output file : " + outputFile + " is successfully saved ");

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
AppsB app = new AppsB();
app.createAndListenSocket();
}
}

Figure 2b(2) receive file


Step 5 : Open Eclipse and type the code in Figure 2b(3). The source code of
FileEvent.java is the interface coding for communication between AppsA.java
and AppsB.java

import java.io.Serializable;

public class FileEvent implements Serializable {

public FileEvent() {}

private static final long serialVersionUID = 1L;

private String destinationDirectory;


private String sourceDirectory;
private String filename;
private long fileSize;
private byte[] fileData;
private String status;

public String getDestinationDirectory() {


return destinationDirectory;
}

public void setDestinationDirectory(String destinationDirectory) {


this.destinationDirectory = destinationDirectory;
}

public String getSourceDirectory() {


return sourceDirectory;
}

public void setSourceDirectory(String sourceDirectory) {


this.sourceDirectory = sourceDirectory;
}

public String getFilename() {


return filename;
}

public void setFilename(String filename) {


this.filename = filename;
}
public long getFileSize() {
return fileSize;
}

public void setFileSize(long fileSize) {


this.fileSize = fileSize;
}

public String getStatus() {


return status;
}

public void setStatus(String status) {


this.status = status;
}

public byte[] getFileData() {


return fileData;
}

public void setFileData(byte[] fileData) {


this.fileData = fileData;
}
}

Figure 2b(3) FileEvent

Step 6: Save, compile and run the program

** Students should have 3 files to run this application : AppsA.java, AppsB.java and
FileEvent.java
** Steps to run the application : FileEvent.java (compile & run) -> AppsB.java (compile & run)

Expected Output:

Figure 2b(4): Source

Figure 2b(5): Destination