java实现的利用HTTP协议原理实现的GET/POST请求的web服务器

1.HTTP协议原理

(1)连接

(2)请求

(3)应答

(4)关闭连接

2.为了测试不同的请求,写了两个html文件。

get.html

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Document</title>
 </head>
 <body>
  <h1> I came,I saw ,I conquered.
  </h1>
 </body>
</html>

post.html

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Document</title>
 </head>
 <body>
  <h1> I came,I saw ,I conquered.
  </h1>
<form method = "post">
</form>
 </body>
</html>

测试时,把这两个文件随便放,输入地址栏的时候,如果在本机上,输入:http://localhost:8888/该文件的绝对路径。下面是两个结果图:


如果是有条件的话,在一台机器上面编译执行完WebServer,再另一台机器上打开浏览器软件,输入http://主机名:8888/该文件的绝对路径 。下面是我测试的图。



代码如下;


WebServer.java

package com.wjl;
import java.net.ServerSocket;
import java.net.Socket;


public class WebServer
{
	public static void main(String args[])
	{
		int i = 1, PORT = 8888;
		try
		{
			/*(1) 创建ServerSocket类对象, 监听端口8888 。*/
			ServerSocket server = new ServerSocket(PORT);//创建绑定到特定端口的服务器套接字。
			Socket client = null;// 客户端
			System.out.println("web servet is listening on port "+ server.getLocalPort());// 返回此套接字绑定到的本地端口。
       /*1.连接*/
			for (;;)
			{
				/*(2)等待、接受客户机连接到端口8888,得到与客户机连接的socket*/
				client = server.accept();// 侦听并接受到此套接字的连接(即接受客户机的连接请求)。此方法在连接传入之前一直阻塞。返回:新套接字
				 new ConnectionThread(client, i).start();// 创建新执行线程有两种方法。一种方法是将类声明为Thread 的子类。
				//该子类应重写 Thread 类的 run方法。接下来可以分配并启动该子类的实例.使该线程开始执行;Java 虚拟机调用该线程的 run 方法
				i++;
			}
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

其中的ConnectionThread类代码如下:

package com.wjl;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class ConnectionThread extends Thread
{
	Socket client;//连接WEB浏览器的套接字
	int count;

	public ConnectionThread(Socket client, int count)
	{
		this.client = client;
		this.count = count;
	}

	public void run()
	{
		String destIP = client.getInetAddress().toString();//返回客户端套接字的IP地址
		int destPort = client.getPort();//返回客户端套接字的端口地址
		System.out.println("connection=" + count + " destIP= " + destIP
				+ " destPort=" + destPort);
		try
		{
		/*2.请求*/
		    /*(3)创建与客户端套接字相关联的输入流d和输出流outStream*/
			
			PrintStream outStream = new PrintStream(client.getOutputStream());// 创建新的打印流。
			BufferedReader d = new BufferedReader(new InputStreamReader(client.getInputStream()));// 每次调用 InputStreamReader 中的一个
			// read() 方法都会导致从底层输入流读取一个或多个字节。要启用从字节到字符的有效转换,可以提前从底层流读取更多的字节,使其超过满足当前读取操作所需的字节。
			// 为了达到最高效率,可要考虑在 BufferedReader 内包装 InputStreamReader。
			
			/*(4)从与客户端套接字关联的输入流d中读取一行客户机提交的请求信息,请求信息的格式为:GET/POST 路径/文件名  HTTP1.0*/
			String inline = d.readLine();
			System.out.println("received: " + inline);

	   /*3.应答*/
			/*(5)从请求信息中获取请求类型,如果请求类型是GET/POST,则从请求信息中获取所访问的HTML文件名。*/
			if (getRequest(inline))
			{
				String fileName = getFileName(inline);
				System.out.println("filename=" + fileName);
				File file = new File(fileName);//通过将给定路径名字符串转换为抽象路径名来创建一个新 File实例。
				/*如果HTML文件存在,则打开HTML文件,把HTTP头信息和HTML文件内容通过socket传回给WEB浏览器,然后关闭文件。否则发送错误信息给WEB浏览器*/
				System.out.println(file.exists());   
				if (file.exists())
				{
					//为了告知web浏览器传送内容的类型,web服务器首先传送一些HTTP头信息,然后传送具体内容(即HTTP体信息)
					System.out.println(fileName + "requested");
					outStream.println("HTTP/1.0 200 OK");//这是Web服务器应答的第一行, 列出服务器正在运行的HTTP版本号和应答代码。HTTP/1.0指出WEB浏览器使用的HTTP版本号,200 OK表示请求完成
					outStream.println("MIME-version:1.0");//它指示MIME类型的版本
					outStream.println("Content-Type:text/html");//这个头信息非常重要, 它指示HTTP体信息的MIME类型。如:Content-Type:text/html指示传送的数据是HTML文档。
					int len = (int) file.length();
					outStream.println("Content-Length:" + len);//它指示HTTP体信息的长度(字节)
					outStream.println("");//HTTP头信息与HTTP体信息之间用一个空行分开
					sendFile(outStream, file);
					outStream.flush();
				}
				else
				{
					String notFound = "<html><head><title>Not Found</title></head><body><h1>Error 404-file not found</h1></body></html>";
					outStream.println("HTTP/1.0 404 not found");
					outStream.println("MIME-version:1.0");
					outStream.println("Content-Type:text/html");
					int len = notFound.length();
					outStream.println("Content-Length:" + len + 2);
					outStream.println("");
					outStream.println(notFound);
					outStream.flush();
				}
				long m1 = 1;
				while (m1 < 11100000)
				{
					m1++;
				}
		/*4.关闭连接*/
				/*(7)关闭与相应WEB浏览器连接的socket字*/
				client.close();//当应答结束后,web浏览器与web服务器必须断开,以保证其他WEB浏览器能够与WEB服务器建立连接。
			}
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void sendFile(PrintStream outStream, File file)
	{

		try
		{
			DataInputStream d = new DataInputStream(new FileInputStream(file));
			int len = (int) file.length();
			byte[] buf = new byte[len];
			d.readFully(buf);//从输入流中读取一些字节,并将它们存储在缓冲区数组 b 中。
			outStream.write(buf, 0, len);//将 len 字节从指定的初始偏移量为off=0的 byte数组写入此流。如果启用自动刷新,则调用 flush 方法
			outStream.flush();//刷新该流的缓冲。
			d.close();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private String getFileName(String inline) //请求信息的格式为:GET/POST 路径/文件名  HTTP1.0
	{
		String s = inline.substring(inline.indexOf(" ")+1);//得到路径/文件名  HTTP1.0。" "中间必须是空格。
		//public String substring(int beginIndex)返回一个新的字符串,它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始,直到此字符串末尾。
		//public int indexOf(int ch)返回指定字符在此字符串中第一次出现处的索引。
		s = s.substring(0, s.indexOf(" "));//得到路径/文件名
		//public String substring(int beginIndex,int endIndex)返回一个新字符串,它是此字符串的一个子字符串。该子字符串从指定的 beginIndex 处开始,直到索引 endIndex - 1 处的字符。因此,该子字符串的长度为 endIndex-beginIndex。
		
		try{
		if(s.charAt(0) == '/')//返回指定索引处的 char 值。索引范围为从 0 到 length() - 1
		{
			s = s.substring(1);//得到文件名
		}
		}catch(StringIndexOutOfBoundsException e)
		{
			System.out.println("Exception " + e);
			
		}
		
		System.out.println(s);
		return s;
	}

	private boolean getRequest(String inline)
	{
		if (inline.length() > 0)
		{
			if (inline.substring(0, 3).equalsIgnoreCase("GET") || inline.substring(0, 4).equalsIgnoreCase("POST"))
				return true;
		}
		return false;
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值