多線程Java服務器簡單實現

代碼主要由兩個類構成:html

  1. 服務類,默認開啓一個8089的http服務java

package com.twins.server;

import java.io.IOException;
import java.net.ServerSocket;

public class HttpServer {

	public static void main(String[] args) throws NumberFormatException, IOException {
		ServerSocket ss = new ServerSocket((args.length == 0) ? 8089 : Integer.parseInt(args[0]));
		System.out.println("Service started");
		while(true) {
			new HttpThread(ss.accept()).start();
			//ss.close();
		}
	}
}

 2.Http線程類,封裝每一個Http請求的處理操做socket

package com.twins.server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.util.StringTokenizer;

public class HttpThread extends Thread{
	Socket socket;
	HttpThread(Socket ss) {
		this.socket = ss;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "gbk"));
			OutputStream out = socket.getOutputStream();
			String temp = null;
			
			/** 打印客戶端請求參數 */
			while(!(temp = in.readLine()).equals("")) {
				
				//按行讀取,解析GET協議
				if(temp.contains("GET")) {
					System.out.println(temp + " @"+ socket.getLocalSocketAddress());
					StringTokenizer st = new StringTokenizer(temp, " ");
					if(st.countTokens()>=2 && st.nextToken().equalsIgnoreCase("get")) {
						String path = st.nextToken();
						String filename = null;
						if(path.startsWith("/") && !path.endsWith("/")) {
							filename = path.substring(1);
						
						} else {
							
							/** 默認輸出index.html*/
							filename = "index.html";
						}
						//解析html文本
						if(new File(filename).exists()) {
							InputStream file= new FileInputStream(filename);
							byte[] data = new byte[file.available()];
							file.read(data);
							out.write(data);
						} else {
							out.write(filename.getBytes());
						}
						break;
					}
				}
				
			}
			out.close();
			out.flush();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			try {
				socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
相關文章
相關標籤/搜索