📄 datagramclient.java
字号:
import java.net.*;
import java.util.*;
/*
* Created on 2008-4-12
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
/**
* @author Guest
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class DatagramClient {
/*
* Define the default port for the packet send to.
*/
private static int defaultPort = 8000;
/*
* Define the size of buffer to make sure that one packet contain one byte.
*/
private static int bufferSize = 1;
/*
* To make sure send-and-echo should be repeated 1000 times.
*/
private static int sendTimes = 1000;
/*
* The main(String[]) method.
*/
public static void main(String[] args) {
/*
* Record the current send-and-echo times
*/
int count;
/*
* Record the the number of packets lost and duplicated.
*/
int lostAndDuplicated = 0;
/*
* Contain the average round trip time.
*/
float avgRtt;
/*
* Sign the begining time of the whole send-and echo process.
*/
Date start;
/*
* Sign the ending time of the whole send-and echo process.
*/
Date stop;
/*
* Declarate the send byte.
*/
byte sendBuffer[] = new byte[bufferSize];
/*
* Declarate the receive byte.
*/
byte receiveBuffer[] = new byte[bufferSize];
/*
* The datagram send packet
*/
DatagramPacket sendPacket;
/*
* The datagram receive packet
*/
DatagramPacket receivePacket;
/*
* The datagram client Socket.
*/
DatagramSocket clientSocket;
/*
* The ip address of the server.
*/
InetAddress IPAdd;
try
{
clientSocket = new DatagramSocket();
IPAdd = InetAddress.getByName("127.0.0.1");
clientSocket.setSoTimeout(1000);
sendBuffer[0] = 0;
start = new Date();
for(count =0;count < sendTimes;count++)
{
sendPacket = new DatagramPacket(sendBuffer,bufferSize,IPAdd,defaultPort);
receivePacket = new DatagramPacket(receiveBuffer,receiveBuffer.length);
clientSocket.send(sendPacket);
clientSocket.receive(receivePacket);
while(receiveBuffer[0] != sendBuffer[0])
{
System.err.println("Transmit error!");
count--;
lostAndDuplicated ++;
}
if(sendBuffer[0] < 127)
{
sendBuffer[0]++;
}
else
{
sendBuffer[0] = 0;
}
}
stop = new Date();
avgRtt = (float)(stop.getTime() - start.getTime()) / sendTimes;
System.out.println("The average round trip time is: " + avgRtt + " vs");
System.out.println("The number of packets lost and duplicated is: " + lostAndDuplicated);
clientSocket.close();
}catch(Exception e){
e.printStackTrace();
System.err.println("Error!");
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -