实现简单的多线程HTTP服务器[Java编程]
本文“实现简单的多线程HTTP服务器[Java编程]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:
后期会丰富这个服务器,实现更多的功效,比方:
1.支持POST方法提交
2.支持二进制的传播送
3.支持线程池处理
4.采取NIO非阻塞情势实现
1package thread;
2
3import java.io.BufferedReader;
4import java.io.IOException;
5import java.io.InputStream;
6import java.io.InputStreamReader;
7import java.io.OutputStream;
8import java.io.PrintWriter;
9import java.net.ServerSocket;
10import java.net.Socket;
11
12/** *//**
13 * Copyright (C): 2009
14 * @author 陈新汉
15 * Jun 27, 2009 2:39:39 PM
16 */
17
18/** *//**
19 * Threaded Network Server
20 * 这是一个简单的多线程HTTP服务器
21 * 采取多线程来处理高并发的用户恳求
22 */
23public class HttpServer {
24 public static void main(String [] args){
25 HttpServer hs=new HttpServer();
26 int i=1, port=8888;
27 Socket received=null;
28 try{
29 ServerSocket server=new ServerSocket(port);
30 while(true){
31 received=server.accept();
32 if(received!=null){
33 hs.new ProcessThread(i++,received).start();
34 }
35 }
36 }catch(IOException e){
37 e.printStackTrace();
38 }
39 }
40
41 class ProcessThread extends Thread
42 {
43 private int thread_number=0;
44 private Socket received=null;
45
46 public ProcessThread(int thread_number, Socket received) {
47 super();
48 this.thread_number = thread_number;
49 this.received = received;
50 }
51
52 public void run() {
53 System.out.println("第"+thread_number+"个处理线程启动了……");
54 if(received!=null){
55 try{
56 System.out.println("衔接用户的地址:"+received.getInetAddress().getHostAddress());
57 InputStream in=received.getInputStream();
58 BufferedReader d= new BufferedReader(new InputStreamReader(in));
59 String result=d.readLine();
60 while(result!=null && !result.equals("")){
61 System.out.println(result);
62 result=d.readLine();
63 }
64 OutputStream out=received.getOutputStream();
65 PrintWriter outstream=new PrintWriter(out,true);
66 String msg1="<html><head><title></title></head><body><h1>收到!</h1></body></html>";
67 outstream.println("HTTP/1.0 200 OK");//返回应答消息,并完毕应答
68 outstream.println("Content-Type:text/html;charset=GBK");
69 outstream.println();// 按照 HTTP 协议, 空行将完毕头信息
70 outstream.println(msg1);
71 outstream.flush();
72 outstream.close();
73 }catch(IOException e){
74 e.printStackTrace();
75 }finally{
76 try{
77 received.close();
78 }catch(IOException e){
79 e.printStackTrace();
80 }
81 }
82 }
83 }
84 }
85}
86
运行这个程序启动服务器,然后在浏览器地址栏输入:http://localhost:8888/,便可看到返回后果.
以上是“实现简单的多线程HTTP服务器[Java编程]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |