⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tcpclient.java

📁 SSD8练习3 传上去大家参考参考 研究研究
💻 JAVA
字号:

import java.net.*;
import java.io.*;
import java.util.*;

public class TCPClient{
	
	public static final int SERVICE_PORT = 8000;
	
	public static final int SIZE = 1;
	
	public static void main(String agrs[]){
		
		//declare the times that the packets has been resent
		int duplicated=0;

		//declare the number of total packegs that have been received
		int total=0;
		
		//declare the number of total packegs that have been lost
		int lost = 0;
		//Get an InetAddress for the specified hostname
		
		InetAddress addr = null;
		try{

			//resolve the hostname to an InetAddr
			addr = InetAddress.getByName("localhost");
		}
		catch (UnknownHostException ue){

			System.out.println("Unable to resolve host");
			return;
		}
		try{
			
			String message = "a";
			String get;

			char[] array = message.toCharArray();
			//Get the start time
			Calendar begintime =Calendar.getInstance();	
			for(int i=1;i<=1000;i++){
				
				//Get a socket to send one byte
				Socket clientSocket = new Socket (addr,SERVICE_PORT);
				System.out.println("Connection estavlished");
				//Set the socket option just in case server stalls
				
				clientSocket.setSoTimeout(2000);
				byte[] sendbuf = new byte[SIZE];
				sendbuf[0]= (byte)array[0];
				//sent byte to the server
				
				DataOutputStream outToServer =
								new DataOutputStream(
									clientSocket.getOutputStream());
									
				//put the byte to the outputstream
				outToServer.write(sendbuf,0,1);
				
				System.out.println("Waiting for packge...");
				
				//receive the byte that send from the server
				DataInputStream inFromServer =
					new DataInputStream(clientSocket.getInputStream());
	
				//Declare a timeout flag
				boolean timeout = false;
				try{

					clientSocket.getInputStream();
				}
				catch(InterruptedIOException ioe){

					timeout = true;
				}
				if(!timeout){

					System.out.println("packet received!");
					System.out.println("packet " + i + " is revieved");
					total++;
				}else{
					
						System.out.println("Packet " + i + "is lost!");
						lost++;
				}
				clientSocket.close();
			}
			//Get the stop time
			Calendar endtime = Calendar.getInstance();
			Date d1 = begintime.getTime();
			Date d2 = endtime.getTime();
			long l1 = d1.getTime();
			long l2 = d2.getTime();
			double differ = Math.abs(l2-l1);
			//calculate the average time
			double average = differ/1000;
			System.out.println("The total packages that have been received is " + total + ".");
			System.out.println("The total packates that have been lost is " + lost + ".");
			System.out.println("The average time is :" + average+"ms");	
	
		}
		catch (IOException ioe){

			System.out.println("Socket error " + ioe);
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -