JAVA套接字创建HTTP客户与服务器程序

JAVA套接字创建HTTP客户与服务器程序

套接字:套接字是为了区别不同的应用程序进程和连接,计算机操作系统为TCP/IP协议提供的接口。

HTTPServer.java

package server;
import java.io.*;
import java.net.*;

public class HTTPServer {
public static void main(String args[]) {
	int port;
	ServerSocket serverSocket;
		
	try {
		port=Integer.parseInt(args[0]);
	}
	catch(Exception e) {
		System.out.println("port = 8080");
		port=8080;//默认端口8080
	}
	try {
		serverSocket=new ServerSocket(port);
		System.out.println("服务器正在监听端口: "+serverSocket.getLocalPort());
		
		while(true) {//服务器在一个无限循环中不断接受来自客户的TCP连接请求
			try {
				//等待客户的TCP连接请求
				final Socket socket=serverSocket.accept();
				System.out.println("建立了与客户的一个新的TCP连接,该客户的地址为:"+socket.getInetAddress()
				+":"+socket.getPort());
				service(socket);//响应客户的请求
			}
			catch(Exception e) {
				e.printStackTrace();
			}
		}//#while
	}
	catch(Exception e) {
		e.printStackTrace();
	}
}
//响应客户的请求
public static void service(Socket socket)throws Exception{
	//读取HTTP请求信息
	InputStream socketIn=socket.getInputStream();//得到一个输入流
	Thread.sleep(500);//睡眠500ms,等待HTTP请求
	int size=socketIn.available();//获取输入流字节数
	byte[] buffer=new byte[size];
	socketIn.read(buffer);
	String request=new String(buffer);
	System.out.println(request);
	
	/*解析HTTP请求*/
	//获得HTTP请求的第一行
	String firstLineOfRequest=request.substring(0, request.indexOf("\r\n"));
	//解析HTTP请求的第一行
	String[] parts=firstLineOfRequest.split(" ");
	String uri=parts[1];
	
	/*决定HTTP响应正文的类型*/
	String contentType;
	if(uri.indexOf("html")!=-1||uri.indexOf("htm")!=-1)
		contentType="text/html";
	else if(uri.indexOf("jpg")!=-1||uri.indexOf("jpeg")!=-1)
		contentType="image/jpg";
	else if(uri.indexOf("gif")!=-1)
		contentType="image/gif";
	else
		contentType="application/octet-stream";
	
	/*创建HTTP响应结果*/
	//HTTP响应的第一行
	String responseFirstLine="HTTP/1.1 200 OK\r\n";
	//HTTP响应头
	String responseHeader="Content-Type:"+contentType+"\r\n\r\n";
	//获得读取响应正文的输入流
	InputStream in=HTTPServer.class.getResourceAsStream("./root/"+uri);
	
	/*发送HTTP响应结果*/
	OutputStream socketOut=socket.getOutputStream();
	//发送HTTP响应的第一行
	socketOut.write(responseFirstLine.getBytes());
	//发送HTTP响应的头
	socketOut.write(responseHeader.getBytes());
	//发送HTTP响应的正文
	int len=0;
	buffer=new byte[128];
	while((len=in.read(buffer))!=-1)
		socketOut.write(buffer, 0, len);
	
	Thread.sleep(1000);
	socket.close();
	
}
}

HTTPClient.java

package client;
import java.net.*;
import java.io.*;
public class HTTPClient {
	public static void main(String args[]) {
		//确定HTTP请求的uri
		String uri="Trip.html";
		if(args.length!=0)
			uri=args[0];
		doGet("localhost",8080,uri);//按照GET请求方式访问HTTPServer
	}
	/**按照GET请求方式访问HTTPServer*/
	public static void doGet(String host,int port,String uri){
		Socket socket=null;
	
	try {
		socket=new Socket(host,port);
	}
	catch(Exception e) {
		e.printStackTrace();
	}
	
	try {
		/*创建HTTP请求*/
		StringBuffer sb=new StringBuffer("GET "+uri+" HTTP/1.1\r\n");
		//HTTP请求头
		sb.append("Accept: */*\r\n");
		sb.append("Accept-Language: zh-cn\r\n");
		sb.append("Accept-Encoding: gizp, deflate\r\n");
		sb.append("User-Agent: HTTPClicent\r\n");
		sb.append("Host: localhost:8080\r\n");
		sb.append("Connection: Keep-Alive\r\n\r\n");
		
		/*发送HTTP请求*/
		OutputStream socketOut=socket.getOutputStream();
		socketOut.write(sb.toString().getBytes());
		
		Thread.sleep(2000);
		
		/*接收响应结果*/
		InputStream socketIn=socket.getInputStream();
		int size=socketIn.available();
		byte[] buffer=new byte[size];
		socketIn.read(buffer);
		System.out.println(new String(buffer));
	}
	catch(Exception e) {
		e.printStackTrace();
	}
	finally {
		try {
			socket.close();
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}
}
}

DOS窗口效果:
在这里插入图片描述
在这里插入图片描述
除了用自己写的Client访问Server,也能用浏览器,在浏览器中输入:

http://localhost:8080/Trip.html

浏览器效果:
浏览器效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值