1.核心API
public static void main(String[] args) {
String hostname="192.168.1.104";
try {
ServerSocket sso=new ServerSocket(8080,1,InetAddress.getByName(hostname));
Socket socket = sso.accept();
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2.设计理念
程序的死循环(暴力的做法)来实现不断的获取80端口http请求,来达到监听80端口http请求的目的。java.net包下面的Socket和ServerSocket两个类就能实现我们对8080端口的监听。
设计请求url封装和响应的输出封装。
3.Codding:
3.1Request
/**
* @author Administrator
*
*/
package com.hecore.request;
import java.io.IOException;
import java.io.InputStream;
public class Request
{
private InputStream input;
private String uri;
public Request(InputStream input) {
this.input = input;
}
public String parse()
{
StringBuffer request = new StringBuffer(2048);
int i;
byte[] buffer = new byte[2048];
try
{
i = input.read(buffer);
}
catch(IOException e)
{
e.printStackTrace();
i = -1;
}
for (int j=0; j<i; j++)
{
request.append((char) buffer[j]);
}
System.out.print(request.toString());
uri = parseUri(request.toString());
return request.toString();
}
private String parseUri(String requestString)
{
int index1, index2;
index1 = requestString.indexOf(' ');
if (index1 != -1) {
index2 = requestString.indexOf(' ', index1 + 1);
if (index2 > index1)
return requestString.substring(index1 + 1, index2);
}
return null;
}
public String getUri()
{
return uri;
}
}
3.2Response
/**
* @author Administrator
*
*/
package com.hecore.response;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import com.hecore.request.Request;
import com.hecore.server.HttpServer;
public class Response {
private static final int BUFFER_SIZE = 1024;
Request request;
OutputStream output;
String parse;
public Response(OutputStream output) {
this.output = output;
}
public void setRequest(Request request) {
this.request = request;
}
public void setParse(String parse) {
this.parse = parse;
}
public void sendStaticResource() throws IOException {
byte[] bytes = new byte[BUFFER_SIZE];
FileInputStream fis = null;
FileOutputStream fos=null;
try {
File file = new File(HttpServer.WEB_ROOT, request.getUri());
System.out.println(file.getAbsolutePath());
if (file.exists()) {
fis = new FileInputStream(file);
File f=new File("1.txt");
f.delete();
f.createNewFile();
System.out.println(f.getAbsolutePath());
fos = new FileOutputStream(f);
int ch = fis.read(bytes, 0, BUFFER_SIZE);
//加上http响应头
String responseHead = "HTTP/1.1 200 ok\r\nContent-Type: text/html\r\nContent-Length: "+file.length()+"\r\n\r\n";
output.write(responseHead.getBytes());
fos.write(responseHead.getBytes());
while (ch != -1) {
fos.write(bytes, 0, ch);
output.write(bytes, 0, ch);
System.out.println(ch);
ch = fis.read(bytes, 0, BUFFER_SIZE);
}
} else {
String errorMessage = "HTTP/1.1 404 File Not Found\r\n" + "Content-Type: text/html\r\n"
+ "Content-Length: 23\r\n" + "\r\n" + "<h1>File Not Found</h1>";
// String errorMessage="File Not Found";
output.write(errorMessage.getBytes());
}
} catch (Exception e) {
System.out.println(e.toString());
} finally {
if (fis != null) {
fis.close();
}
if (fos!=null) {
fos.close();
}
}
}
}
3.3 HttpServer
if (null!=request.getUri()) {
shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
} package com.hecore.server;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import com.hecore.request.Request;
import com.hecore.response.Response;
public class HttpServer {
public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "WebRoot";
private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
private boolean shutdown = false;
public static void main(String[] args) {
//System.out.println("1");
HttpServer httpServer = new HttpServer();
httpServer.await();
}
public void await() {
ServerSocket serverSocket = null;
Integer port = 8080;
try {
serverSocket = new ServerSocket(port, 1, InetAddress.getByName("192.168.1.104"));
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
while (!shutdown) {
Socket socket = null;
InputStream input = null;
OutputStream output = null;
try {
socket = serverSocket.accept();
input = socket.getInputStream();
output = socket.getOutputStream();
Request request = new Request(input);
String parse = request.parse();
Response response = new Response(output);
response.setRequest(request);
response.setParse(parse);
response.sendStaticResource();
socket.close();
if (null!=request.getUri()) {
shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
}
} catch (Exception e) {
e.printStackTrace();
continue;
}
}
}
}
4.index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div style="width:100%;margin:0px auto;text-align:center">This is my tomcat</div>
</body>
</html>
5.项目截图