자바, socket 으로 http 서버 만 들 기
3505 단어 java-util
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class HttpServer {
private static final Integer port = 80;//HTTP 80
public static void main(String[] args) {
ServerSocket serverSocket;
try {
// Socket,
serverSocket = new ServerSocket(port);
System.out.println(" :"+serverSocket.getLocalPort());
//
while(true){
final Socket socket = serverSocket.accept();
System.out.println(" , :"+
socket.getInetAddress()+":"+socket.getPort());
// HTTP
service(socket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void service(final Socket socket)
{
new Thread(){
public void run(){
InputStream inSocket;
try {
// HTTP
inSocket = socket.getInputStream();
int size = inSocket.available();
byte[] buffer = new byte[size];
inSocket.read(buffer);
String request = new String(buffer);
System.out.println("ClientBrowser:
"+request+"
"
+ "------------------------------------------------------------------");
String firstLineOfRequest = ""; //http
String[] heads; //
String uri = "/index.html";
String contentType ="";
if(request.length() > 0){
firstLineOfRequest = request.substring(0,request.indexOf("\r
"));
heads = firstLineOfRequest.split(" ");
uri = heads[1];
if(uri.indexOf("html") != -1){
contentType = "text/html";
}else{
contentType = "application/octet-stream";
}
}
System.out.println("http :"+request.substring(request.indexOf("\r
"),request.length()));
//
String responseFirstLine = "HTTP/1.1 200 OK\r
";
String responseHead = "Content-Type:" + contentType +"\r
";
OutputStream outSocket = socket.getOutputStream();
System.out.println("ServerResponse:
"+responseFirstLine+"
"+responseHead+"
"
+ "--------------------------------------------------------------------");
outSocket.write(responseFirstLine.getBytes());
outSocket.write(responseHead.getBytes());
// HTTP uri
FileInputStream writehtml = new FileInputStream(new File("wwwroot"+uri));
outSocket.write("\r
".getBytes());
byte[] htmlbuffer = new byte[writehtml.available()];
if(writehtml !=null){
int len = 0;
System.out.println("writeHtml");
while((len = writehtml.read(htmlbuffer)) != -1){
outSocket.write(htmlbuffer, 0,len);
}
}
outSocket.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}