简单的JavaWeb静态页面服务器,客户端请求示例
2017-04-28 本文已影响0人
hackywit
服务器端
package httpProxyServer;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class HttpServer {
public static void main(String[] args) {
// test,我们先用helloWorld测试一下
int port;// 定义服务器需要绑定的本地端口号
ServerSocket serverSocket;// 定义服务器套接口对象
// 不得不吐槽这异常抛的真不正规
try {
port = Integer.getInteger(args[1]);// 将第二个命令行参数转化为整数
} catch (Exception e) {
System.out.println("port = 8888 (默认)");
port = 8888;
}
try {
serverSocket = new ServerSocket(port);
System.out.println("服务器正在监听端口:" + serverSocket.getLocalPort());
while (true) {
try {
final Socket socket = serverSocket.accept();
System.out.println("建立了与客户的新的TCP连接,该客户的地址为:" + socket.getInetAddress() + ":" + socket.getPort());
service(socket);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void service(Socket socket) throws Exception {
// 读取http请求信息
InputStream socketIn = socket.getInputStream();// 创建输入流通道
Thread.sleep(500);
int size = socketIn.available();// 获取输入流中缓存的大小
byte[] buffer = new byte[size];// 根据缓存大小在缓存外面建立缓存buffer
socketIn.read(buffer);// 读取缓存信息到buffer中
String request = new String(buffer);// 将缓存buffer中的字节放到字符串中
System.out.println(request);// 输出字符串
// 解析http请求信息
String firstLineOfRequest = request.substring(0, request.indexOf("\n\r"));
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/jpeg";
else if(uri.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/" + uri);//读取指定位置的文件到输入流,这边需要注意的是路径,/代表是项目目录,没有代表当前类所在的目录
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 httpProxyServer;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class HttpClient {
public static void main(String[] args) {
String uri = "index.html";
if(args.length != 0) uri=args[0];//这边需要区别c语言下的参数,这边的第一个参数是不包括命令行自身的。
doGet("localhost",8888,uri);
}
private 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");
sb.append("Accept: */*\r\n");
sb.append("Accept-Encoding: gzip,deflate\r\n");
sb.append("Accept-Language: zh-cn\r\n");
sb.append("User-Agent: HTTPClient\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();
}
}
}
}