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

📄 client.java

📁 卡耐基梅陇大学ssd8Exercise1答案
💻 JAVA
字号:
/**
 * @author Gong Xueshen
 * @see <code>Server.java</code>
 * @version 1.0
 * 
 */

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

public class Client{
	// The port number in static final type. 
	private static final int  socketPort = 6789;
	
	// Default constructor.
	public Client(){}

	public void sendMessage(Socket clientSocket, String message){
		String clientRequest;
		System.out.println(message + " is listening to your request:\n");

		BufferedReader inFromClient = new BufferedReader(new InputStreamReader(System.in));
		
		/* In "Try-Catch" block, we do the actual work to send the message out, 
		 * and when the IO erro countered, throw out "IOException". 
		 */
		try{
			DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
			clientRequest = inFromClient.readLine();
			outToServer.writeBytes(clientRequest + "\r\n\r\n");

		}catch(IOException ioe){
			System.err.println("IOException: ");
			ioe.printStackTrace();
		} 
	}
	
	public void header(InputStream inFromServer){
		String header = "";
		int temp;
		boolean isHeader = false;
		
		try{
			temp = inFromServer.read();
			System.out.println(temp);
			header += (char) temp;
			
			// When the string is "\r\n\r\n", the header is over, and we get it.
			while(temp != -1 && !isHeader){
				switch(temp){
				case 13:
					temp = inFromServer.read();
					switch(temp){
					case 10:
						header += (char) temp;
						if((char)(temp = inFromServer.read()) == ('\r'))
							if((char)(temp = inFromServer.read()) == ('\n'))
								isHeader = true;
						break;
					default:
						break;
					}
					break;
				default:
					break;
				}
				if(isHeader)
					break;
				temp = inFromServer.read();
				header += (char) temp;
			}
		}catch(IOException ioe){
			System.err.println("IOException: ");
			ioe.printStackTrace();
		}
			System.out.println("header:\n" + header + "\n");
	}

	public byte[] serverReply(InputStream inFromServer, Socket clientSocket){
		int fileLength=0;
		byte[] buffer = null;
		
		/* Get the length of the flow that come from the 
		 * server and it may cause the IOException.
		 */
		try{
			fileLength = inFromServer.available();
		}catch(IOException e){
			System.err.println("IO erro when \"inFromServer.available()\" ");
			e.printStackTrace();
		}
		
		buffer = new byte[fileLength];
		DataInputStream receivedFile = null; 

		receivedFile = new DataInputStream(inFromServer);
			
		// Get every byte from the DataInputStream object to the buffer array.
		try{
			for(int i = 0; i < buffer.length; i++){
					buffer[i] = receivedFile.readByte();
			 }
		}catch(EOFException eof){
			eof.printStackTrace();
		}catch(IOException e2){
			e2.printStackTrace();
		}
		return buffer;
	}

	public void saveFile(BufferedReader inFromClient, byte[] buffer){
		System.out.println("Input a file name to save the header:\n");
		
		// Write the infomation to the file whose name is inputed by the user.
		try{
			FileOutputStream fileout = new FileOutputStream(inFromClient.readLine());
			PrintStream ps = new PrintStream(fileout);
			ps.write(buffer);
			ps.close();
		}catch (FileNotFoundException fnfe){
			System.err.println("The specified file is not exist!");
			fnfe.printStackTrace();
		}catch(IOException ioe){
			System.err.println("IO erro: ");
			ioe.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws Exception{
		// Creat a new Client object.
		Client client = new Client();
		Socket clientSocket = null;

		// Establish a socket connection.
		try{
			clientSocket = new Socket("host", socketPort);
		}catch(UnknownHostException unke){
			System.err.println("The host is unknown!");
			unke.printStackTrace();
		}catch(IOException ioe){
			System.err.println("IO erro: ");
			ioe.printStackTrace();
		}

		BufferedReader inFromClient = new BufferedReader(new InputStreamReader(
				System.in));

		InputStream inFromServer  = new BufferedInputStream(clientSocket.getInputStream());
		
		client.sendMessage(clientSocket, args[0]);						// Send message.
		client.header(inFromServer);									// Get header.
		byte[] buffer = client.serverReply(inFromServer, clientSocket); // Change the stream flow to the type of "byte"
		client.saveFile(inFromClient, buffer);							// Save file
		clientSocket.close();											// Close the connection.
	}
}

⌨️ 快捷键说明

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