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

来源:互联网 发布:教英语发音的软件 编辑:程序博客网 时间:2024/04/29 23:39
package server;import java.io.*;import java.net.*;/** * @version 2013-11-15 * @author cy * 实现一个http服务器,接收客户端的http请求,打印到控制台,然后解析请求,向客户端返回相应 */public class HTTPServer {public static void main(String[] args){//端口号int port;ServerSocket serverSocket;try{port = Integer.parseInt(args[0]);}catch(Exception e){//默认端口号port = 8880;System.out.println("port = 8880(默认)");}try{serverSocket = new ServerSocket(port);System.out.println("服务器正在监听端口:"+serverSocket.getLocalPort());//不断接收客户端的http请求while(true){try{//等待客户端的TCP请求连接final Socket socket = serverSocket.accept();System.out.println("建立了与客户端的一个新的TCP连接,该客户的地址为:"+socket.getInetAddress()+":"+socket.getPort());//响应客户端请求HTTPServer.service(socket);}catch(Exception e){e.printStackTrace();}}}catch(Exception e){e.printStackTrace();}}/** * 相应客户端的请求 * @param socket 传入的套接字 * @throws Exception */public static void service(Socket socket) throws Exception{//获得输入流InputStream socketIn = socket.getInputStream();Thread.sleep(500);int size = socketIn.available();byte[] buffer = new byte[size];socketIn.read(buffer);String request = new String(buffer);//打印请求System.out.println(request);/* * 解析http请求 */String firstLineOfRequest = request.substring(0,request.indexOf("\r\n"));String[] parts = firstLineOfRequest.split(" ");String url = parts[1];String contentType;if(url.indexOf("html") != -1 || url.indexOf("htm") != -1)contentType = "text/html";else if(url.indexOf("jpg") != -1 || url.indexOf("jpeg") != -1)contentType = "image/jpeg";else if(url.indexOf("gif") != -1)contentType = "image/gif";else//省略其他类型contentType = "application/octet-stream";//http响应第一行String responseFirstLine = "HTTP/1.1 200 ok\r\n";//响应头String responseHeader = "Content-Type:"+ contentType + "\r\n\r\n";//获得读取响应正文数据的输入流InputStream in = HTTPServer.class.getResourceAsStream("root/"+url);OutputStream socketOut = socket.getOutputStream();socketOut.write(responseFirstLine.getBytes());socketOut.write(responseHeader.getBytes());int len =0;buffer = new byte[128];while((len = in.read(buffer)) != -1){socketOut.write(buffer,0,len);}Thread.sleep(1000);socket.close();}}
package client;import java.net.*;import java.io.*;import java.util.*;public class HTTPClient {public static void main(String[] args) {String url = "index.htm";if (args.length != 0)url = args[0];doGet("localhost", 8880, url);}public static void doGet(String host, int port, String url) {Socket socket = null;try {socket = new Socket(host, port);} catch (Exception e) {e.printStackTrace();}try {/* 按照GET请求方式访问HTTPServer */StringBuffer sb = new StringBuffer("GET" + " " + url + " "+ "HTTP/1.1\r\n");sb.append("Accept: */*\r\n");sb.append("Accept-Language: zh-cn\r\n");sb.append("Accept-Encoding: gzip,deflate\r\n");sb.append("User-Agent: HTTPClient\r\n");sb.append("Host: localhost:8880\r\n");sb.append("Connection: Keep-Alive\r\n\r\n");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, "UTF-8"));} catch (Exception e) {e.printStackTrace();} finally {try {socket.close();} catch (Exception e) {e.printStackTrace();}}}}


	
				
		
原创粉丝点击