?? datagramclient.java
字號(hào):
/*
* Created on 2007-5-26
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
import java.io.*;
import java.net.*;
import java.util.*;
/**
* @author Guest
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class DatagramClient {
/**
* the count of packet
*/
private int count;
/**
* duplicate packet
*/
private int duplicate;
/**
* lost count of packet
*/
private int lost;
/**
* the time before send packet
*/
private Date start;
/**
* the time while stop send packet
*/
private Date stop;
/**
* datagramSocket
*/
private DatagramSocket socket;
/**
* datagramPacket
*/
private DatagramPacket outToServer;
private DatagramPacket inFromServer;
/**
* the byte packet
*/
private byte out[] = new byte[1];
private byte in[] = new byte[1];
/**
* byte number
*/
protected byte temp;
/**
* DatagramClient constructor
* <p>initialize </p>
*/
DatagramClient(){
count = 0;
duplicate = 0;
lost = 0;
temp = 0;
out[0] = temp;
}
/**
* send packet to server
* @param host the hostIP of the server
*/
void sendPacket(InetAddress host){
try {
socket = new DatagramSocket();
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
start = new Date();
for(; count < 1000; out[0] = (byte)(count % 128)){
try {
outToServer = new DatagramPacket(out, out.length, host, 8000);
inFromServer = new DatagramPacket(in, in.length);
socket.send(outToServer);
socket.setSoTimeout(1000);
socket.receive(inFromServer);
in = inFromServer.getData();
temp = in[0];
if(temp == out[0]){
count++;
}else{
lost++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println(e);
}
}
stop = new Date();
}
/**
*
* <p>Print out the average round trip time,
* as well as the number of packets lost and duplicated.</p>
*/
void out(){
double aveTime = (double)(stop.getTime() - start.getTime())/1000;
System.out.println("The average round trip time is: " + aveTime);
System.out.println("The number of lost packets is: " + lost);
//System.out.println("The number of duplicate packets is: " + duplicate);
}
/**
* Close the DatagramSocket
*
*/
void close(){
try {
socket.close();
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
* @param args
*/
public static void main(String[] args) throws IOException {
if(args.length != 1){
System.out.println("Only need one argument!");
return;
}
DatagramClient client = new DatagramClient();
try {
InetAddress host = InetAddress.getByName(args[0]);
client.sendPacket(host);
client.out();
client.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -