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

📄 server.java~

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

/**
 * This is a server creating a socket with port number 8000 and waits for
 * incoming requests.
 */
public class Server {

	private static String CRLF = "\r\n";

	/**
	 * The main function of the class.
	 */
	public static void main(String[] args) {
		Server server = new Server();
		try {
			server.processRequest();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * This method is used to processRequest from the client or user.
	 */
	private void processRequest() throws Exception {

		/**
		 * The server socket banding to port 8000.
		 */
		ServerSocket listenSocket = new ServerSocket(8000);

		/**
		 * Infinate loop for accepting incoming connections. Handle one request
		 * at a time.
		 */
		while (true) {
			/*
			 * Print the prompt message in the terminal.
			 */
			System.out.println("The server is now waiting for request...");

			Socket connectionSocket = listenSocket.accept();

			/**
			 * Receive the request message from the client.
			 */
			String requestMessage = "";

			boolean readFinish = false;
			/*
			 * The buffer reader used to get request message from the client.
			 */
			DataInputStream inFromClient = new DataInputStream(connectionSocket
					.getInputStream());

			/*
			 * the output stream used to export to the client terminal.
			 */
			DataOutputStream outToClient = new DataOutputStream(
					connectionSocket.getOutputStream());

			/*
			 * get the request message.
			 */
			requestMessage = inFromClient.readLine().toString();


			/*
			 * parse the ruquest message.
			 */
			StringTokenizer tokenizedline = new StringTokenizer(requestMessage);

			String command = tokenizedline.nextToken();

			/*
			 * If it is a GET request.
			 */
			if (command.equals("GET")) 
			{
				String url = tokenizedline.nextToken();
				String httpVersion = tokenizedline.nextToken();
				
				processGet(outToClient, url);

			} else if (command.equals("PUT")) 
			{
				int len = 0;
				
				String url = tokenizedline.nextToken();
	
				StringTokenizer tokens = new StringTokenizer(requestMessage,CRLF);

				while (tokens.hasMoreTokens()) 
				{
					String token = tokens.nextToken();
					if (token.startsWith("Content-Length:")) 
					{
						String lengthStr = token
								.substring(token.indexOf(' ') + 1);
						len = new Integer(lengthStr).intValue();
						break;
					}
				}

				if (len > 0) 
				{
					
					processPut(inFromClient, outToClient, url, len);
				} else 
				{
					outToClient.write(buildErrorPage(400, "Bad Request.").getBytes());
				}
			} else 
			{
				outToClient.write((buildErrorPage(501, "Not Implemented")).getBytes());
			}
		}
	}

	private void processPut(DataInputStream inFromClient,
			DataOutputStream outToClient, String filename, int len) 
	{
		try {
			
			if (filename.startsWith("/") == true)
				filename = filename.substring(1);

			File file = new File(filename);
			
			String feedback;
			
			if (file.exists()) 
			{
				if (!file.isFile()) 
				{
					outToClient.write((buildErrorPage(403, "Forbidden")).getBytes());
					return;
					
				} else 
				{
					feedback = buildErrorPage(200, "OK");
				}
			} else {
				feedback = buildErrorPage(201, "Created");
			}

			/**
			 * Create a file stream.
			 */
			FileOutputStream fstream = new FileOutputStream(file);
			
			byte[] buffer = new byte[1000];
			int count = 0;
			
			while (count < len && ((count += inFromClient.read(buffer)) != -1)) 
			{
				fstream.write(buffer);
			}
			/**
			 * Be sure to flush the output stream.
			 */
			fstream.flush();
			outToClient.write(feedback.getBytes());
			
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	private void processGet(DataOutputStream outToClient, String filename) {
		try {
			if (filename.startsWith("/") == true)
				filename = filename.substring(1);

			File file = new File(filename);
			/**
			 * if the file not found
			 */
			if (!file.isFile()) 
			{
				outToClient.write(buildErrorPage(404, "Not Found " + filename)
						.getBytes());
			} else 
			{
				
				int numberOfBytes = (int) file.length();

				FileInputStream inFile = new FileInputStream(filename);

				byte[] fileInBytes = new byte[numberOfBytes];

				inFile.read(fileInBytes);

				outToClient.writeBytes("HTTP/1.0 200 OK" + CRLF);

				if (filename.endsWith(".jpg") || filename.endsWith(".JPG"))
					outToClient.writeBytes("Content-type:" + "image/jpeg"
							+ CRLF);

				if (filename.endsWith(".gif") || filename.endsWith(".GIF"))
					outToClient
							.writeBytes("Content-type:" + "image/gif" + CRLF);

				if (filename.endsWith(".htm") || filename.endsWith(".html"))
					outToClient
							.writeBytes("Content-type:" + "text/html" + CRLF);

				outToClient
						.writeBytes("Content-Length:" + numberOfBytes + CRLF);

				outToClient.writeBytes(CRLF);
				
				outToClient.write(fileInBytes, 0, numberOfBytes);

			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}


	private String buildErrorPage(int ErrorNo, String msg) 
	{
		String content = "<html>" + CRLF + "<head>" + CRLF
				+ "   <title>Java Http 1.0 Server- Error report </title>"
				+ CRLF + "</head>" + CRLF + "<body>" + CRLF
				+ "   <h1>HTTP Status " + ErrorNo + "\n" + msg + "</h1>" + CRLF
				+ "</body>" + "</html>" + CRLF;

		String header = "HTTP/1.0" + " " + ErrorNo + " " + msg + CRLF;

		header += ("Content-type: text/html" + CRLF);

		header += ("Content-Length:" + content.length() + CRLF + CRLF);

		return (header + content);
	}

}

⌨️ 快捷键说明

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