多线程Java服务器简单实现

代码主要由两个类构成:

  1. 服务类,默认开启一个8089的http服务

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请求的处理操作

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();
			}
		}
	}
}

 

转载于:https://my.oschina.net/u/250670/blog/279929

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值