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

📄 threadedserver.java~

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

/**
 * This is a server creating a socket with port number 8000 
 * and waits for incoming requests. 
 * I can work With multiple threads.
 */
public class ThreadedServer 
{
	/**
	 * the main function.
	 */
	public static void main(String[] argv)throws Exception
	{
		/**
	     * The server socket banding to port 8000.
	     */
		ServerSocket listenSocket = new ServerSocket(8000);
		
		/*
		 * Print the prompt message in the terminal.
		 */
		System.out.println("The server is now waiting for request...");
		
		while(true)
		{
			
			Socket connectionSocket = listenSocket.accept();
			
			System.out.println("Accepting Connection...\n");
			
			// Start a thread to handle the connection.

			new ServerThread(connectionSocket);
			
		}

	}
}

class ServerThread implements Runnable 
{
	/**
	 * The socket which promot the thread.
	 */
	private Socket socket;
	
	private static String CRLF = "\r\n";
	
	/**
	 * The request message.
	 */
	private String requestMsg;

	/**
	 * the Constructor
	 * @param s the socket
	 */
	public ServerThread(Socket s) 
	{
		Thread t;
		this.socket = s;
		t = new Thread(this, "Handler Thread");
		t.start();
		 
	}


	public void run() 
	{
		try 
		{
			String requestMessage = "";

			boolean readFinish = false;

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

			/*
			 * the output stream used to export to the client terminal.
			 */
			DataOutputStream outToClient = new DataOutputStream(
					socket.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();
				
				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());
			}
		}catch(IOException e)
		{
			e.printStackTrace();
		}

	}
	
	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 + -