java用socket来做http服务器(2)

服务端代码:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class HTTPServer {

	public static void main(String[] args) {
		try {
			System.out.println("服务器开启");
			ServerSocket ss = new ServerSocket(8889);
			while (true) {
				Socket socket = ss.accept();
		        System.out.println("接收到一个请求,请求地址:"+  
		                socket.getInetAddress()+":"+socket.getPort()); 
				BufferedReader bd = new BufferedReader(new InputStreamReader(
						socket.getInputStream(), "UTF-8"));

				/**
				 * 接受HTTP请求
				 */
				String requestHeader;
				int contentLength = 0;
				while ((requestHeader = bd.readLine()) != null
						&& !requestHeader.isEmpty()) {
					System.out.println("报文头数据:" + requestHeader);
					if (requestHeader.startsWith("POST")) {
						System.out.println("该请求为POST请求");
					}
					if (requestHeader.startsWith("GET")) {
						System.out.println("该请求为GET请求");
					}
					if (requestHeader.startsWith("Content-Length")) {//只有Post请求会有这个信息
						int begin = requestHeader.indexOf("Content-Lengh:")
								+ "Content-Length:".length();//判断报文头参数Content-Length的起始位置
						String postParamterLength = requestHeader.substring(
								begin + 1).trim();//获取报文头参数信息的长度
						contentLength = Integer.parseInt(postParamterLength);
						System.out.println("POST参数长度是:"
								+ Integer.parseInt(postParamterLength));
					}
				}

				StringBuffer sb = new StringBuffer();
				if (contentLength > 0) {//如果是Post请求,打印客户端数据
					for (int i = 0; i < contentLength; i++) {
						sb.append((char) bd.read());
					}
					System.out.println("http服务端接收客户端数据:" + sb.toString());
				}

				System.out.println("发送回执");
				// 发送回执
				OutputStream out = socket.getOutputStream();
				StringBuffer pw = new StringBuffer();
				pw.append("HTTP/1.1 200 OK" + "\r\n");
				pw.append("Content-type:text/html" + "\r\n");
				pw.append("\r\n");
				// 返回客户端的数据
				String resJson = "server return value";
				System.out.println("http服务器返回客户端数据:" + resJson);
				pw.append(resJson);
				String ResMsg = pw.toString();
				out.write(ResMsg.getBytes("GBK"));

				socket.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

测试:

          可以写一个http客户端代码,也可以直接用浏览器访问,地址:http://localhost:8889/XXX

 

测试结果:

         客户端代码访问结果:

服务器开启
接收到一个请求,请求地址:/127.0.0.1:58122
报文头数据:POST /SSM_HTTPS HTTP/1.1
该请求为POST请求
报文头数据:Charset: UTF-8
报文头数据:Content-Type: application/json; charset=UTF-8
报文头数据:accept: application/json
报文头数据:Cache-Control: no-cache
报文头数据:Pragma: no-cache
报文头数据:User-Agent: Java/1.6.0_45
报文头数据:Host: localhost:8889
报文头数据:Connection: keep-alive
报文头数据:Content-Length: 16
POST参数长度是:16
http服务端接收客户端数据:1234567890098765
发送回执
http服务器返回客户端数据:server return value

 

          浏览器访问结果:

————————————————————————————————————————————————————————

接收到一个请求,请求地址:/0:0:0:0:0:0:0:1:58330
报文头数据:GET /XXX HTTP/1.1
该请求为GET请求
报文头数据:Accept: image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/xaml+xml, application/x-ms-xbap, */*
报文头数据:Accept-Language: zh-CN
报文头数据:User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)
报文头数据:Accept-Encoding: gzip, deflate
报文头数据:Host: localhost:8889
报文头数据:Connection: Keep-Alive
发送回执
http服务器返回客户端数据:server return value

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值