?? datagramclient.java
字號(hào):
/**
* This class models a client using UDP to communite with the server.
*
* @author tyrant
* @version 1.0.0
*/
import java.net.*;
public class DatagramClient {
/* datagram socket to communicate with the server. */
private DatagramSocket clientSocket;
/* the time out for the datagram socket*/
private static final int TIME_OUT = 5;
/**
* constructor to create the socket and set the time out.
* @throws SocketException
*/
public DatagramClient() throws SocketException {
clientSocket = new DatagramSocket();
clientSocket.setSoTimeout(TIME_OUT);
}
/**
* method to exchange one byte with the server for 1000 times.
* @throws Exception
*/
public void run() throws Exception {
long totalTime = 0;
long startTime = 0;
long endTime = 0;
int counterOfPacket = 1;
int numberOfLost = 0;
int numberOfDuplicate = 0;
boolean reSend = true;
/* byte arrays to store one byte to receive and to send. */
byte[] sendByte = new byte[1];
byte[] receiveByte = new byte[1];
sendByte[0] = 'a';
/* get the ip of local host.*/
InetAddress host = InetAddress.getLocalHost();
// get the start time before the while circle.
startTime = System.currentTimeMillis();
while (counterOfPacket <= 1000) {
/*
* resend the byte when it is not sent or received correctly.
*/
while (reSend) {
reSend = false;
// send the packet.
DatagramPacket sendPacket = new DatagramPacket(sendByte,
sendByte.length, host, 6000);
clientSocket.send(sendPacket);
// recieve the packet.
try {
DatagramPacket receivePacket = new DatagramPacket(
receiveByte, receiveByte.length);
clientSocket.receive(receivePacket);
} catch (SocketTimeoutException stoe) {
++numberOfLost;
reSend = true;
}
}
/*
* check if the byte received is expected.
*/
if (sendByte[0] == receiveByte[0]) {
++counterOfPacket;
sendByte[0]++;
reSend = true;
}
/*
* if the byte is not the one expected, receive or resend it.
*/
else {
++numberOfDuplicate;
reSend = false;
try {
DatagramPacket receivePacket = new DatagramPacket(
receiveByte, receiveByte.length);
clientSocket.receive(receivePacket);
} catch (SocketTimeoutException stoe) {
++numberOfLost;
reSend = true;
}
}
}
// get the end time after the while circle.
endTime = System.currentTimeMillis();
totalTime = endTime - startTime;
System.out.println("Total time: " + totalTime + "ms");
System.out.println("RTT: " + totalTime / 1000.0 + "ms");
System.out.println("Number of lost: " + numberOfLost);
System.out.println("Number of duplicate: " + numberOfLost);
clientSocket.close();
}
/**
* @param args
*/
public static void main(String[] args) throws Exception {
DatagramClient client = new DatagramClient();
client.run();
}
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -