📄 tcpclient.java
字号:
import java.io.*;
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 TCPClient {
/*
* 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)throws Exception {
/*
* Record the current send-and-echo times
*/
int count = 0;
/*
* 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 out to server stream.
*/
DataOutputStream outToServer;
/*
* The input from user stream.
*/
DataInputStream inFromUser;
/*
* The TCP client socket.
*/
Socket clientSocket;
/*
* Initial the send byte.
*/
sendBuffer[0] = 0;
try{
start = new Date();
for(count = 0;count < sendTimes;count++)
{
clientSocket = new Socket("127.0.0.1",defaultPort);
clientSocket.setSoTimeout(1000);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
inFromUser = new DataInputStream(clientSocket.getInputStream());
outToServer.write(sendBuffer);
outToServer.flush();
inFromUser.read(receiveBuffer);
if(sendBuffer[0] != receiveBuffer[0])
{
count--;
lostAndDuplicated ++;
}
if(sendBuffer[0] < 127)
{
sendBuffer[0]++;
}
else
{
sendBuffer[0] = 0;
}
clientSocket.close();
}
stop = new Date();
avgRtt = (float)(stop.getTime()- start.getTime())/sendTimes;
System.out.println("The number of packets lost and duplicated is: " + lostAndDuplicated);
System.out.println("The average round trip time to send one byte with TCP is: " + avgRtt + " vs");
}catch (SocketTimeoutException ste) {
count--;
lostAndDuplicated ++;;
}catch(Exception e){
e.printStackTrace();
System.err.println("Error!");
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -