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

📄 client.java~

📁 用java编写的http的client和server程序
💻 JAVA~
字号:
/**
 * @(#)Server.java
 *
 * @author Xia Chang'an
 * @version 1.0
 */
import java.io.*;
import java.net.*;

public class Client 
{
	/**
	 * The port of the socket
	 */
	private static int port 	= 80;
	private static String CRLF 	= "\r\n";
	
	public static void main(String argv[]) throws UnknownHostException, IOException
	{
		/**
		 * The request command.
		 */
		String command = "";
		
		/**
		 * The header line.
		 */
		String header = "";
		Socket clientSocket;
		byte [] bytes;
		
		/**
		 * ensure the argument value
		 */
		if(argv.length != 1)
		{
			System.err.println("Usage: Client <server>");
			System.exit(0);
		}
		
		/**
		 * construct a socket banding to the port.
		 */
		clientSocket = new Socket(argv[0], port); 
			
		/**
		 * read from the user input.
		 */
		BufferedReader inFromUser = 
			new BufferedReader(new InputStreamReader(System.in));
		
		/**
		 * read from the server.
		 */
		DataInputStream inFromServer = 
			new DataInputStream(clientSocket.getInputStream());
		
		/**
		 * output to the server.
		 */
		DataOutputStream outToServer = 
			new DataOutputStream(clientSocket.getOutputStream());
		
		/**
		 * print the promot information.
		 */
		System.out.println(argv[0] + " is listening to your request:");
		
		/**
		 * read a line from the user input.
		 */
		command = inFromUser.readLine();
		
		bytes = (command + CRLF + CRLF).getBytes();
		
		/**
		 * write the bytes to the server.
		 */
		outToServer.write(bytes, 0, bytes.length);
		
		/**
		 * flush the stream
		 */
		outToServer.flush();
		
		/**
		 * Get from the respond header from the server.
		 */
		String line;
		while((line = inFromServer.readLine()).length() != 0) 
		{
			header += line;
			header += '\n';
		}	
		
		/**
		 * Print the header to the terminal.
		 */
		System.out.println("Header: \n");
		System.out.print(header + "\n");
		System.out.flush();
		
		System.out.print("Enter the name of the file to save: ");
		System.out.flush();
		String filename = inFromUser.readLine();
		
		FileOutputStream fileOut = null;
		
		/**
		 * creat a new file.
		 */
		if(!filename.isEmpty())
		{
			fileOut = new FileOutputStream(filename);
		}
		else
		{
			System.err.println("File name empty! Exit.");
			System.exit(0);
		}
		try
		{
			/**
			 * print the respond content to the file.
			 */
			byte[] buffer = new byte[1];
			while(inFromServer.read(buffer, 0, buffer.length) != -1)
			{
				fileOut.write(buffer);
			}
			
		} catch(NullPointerException e) {
			e.printStackTrace();
		}
		
		System.out.println("The content has been saved in the file '" + filename + "'.");
		
		/**
		 * Close the stream and the socket.
		 */
		fileOut.close();
		clientSocket.close();
		inFromServer.close();
		outToServer.close();
	}
	
}

⌨️ 快捷键说明

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