다중 스레드 Java 웹 서버를 구현하려고합니다.다중 스레드 Java 웹 서버
여기 내 주요입니다 :
import java.net.*;
public class Main {
public static void main(String argv[]) throws Exception{
ServerSocket welcomeSocket = new ServerSocket(6790);
while(true){
System.out.println("Waiting...");
Socket cSock = welcomeSocket.accept();
System.out.println("Accepted connection : " + cSock);
Server a = new Server(cSock);
a.start();
}
}
}
여기 내 스레드 클래스입니다 : 논리에 의해
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Server extends Thread{
Socket cSock;
Server(Socket cSock){ //constructor
this.cSock = cSock;
}
public void run(){
try{
String request;
Scanner inFromClient = new Scanner(cSock.getInputStream());
DataOutputStream outToClient = new DataOutputStream(cSock.getOutputStream());
request = inFromClient.nextLine();
System.out.println("Received: "+request);
//trimming URL to extract file name
String reqMeth = request.substring(0, 3);
String reqURL = request.substring(5, (request.lastIndexOf("HTTP/1.1")));
String reqProto = request.substring(request.indexOf("HTTP/1.1"));
System.out.println("Request Method:\t" +reqMeth +"\nRequest URL:\t" +reqURL+ "\nRequest Protocol: " +reqProto);
//passing file name to open
File localFile = new File(reqURL.trim());
byte [] mybytearray = new byte [(int)localFile.length()];
FileInputStream fis = new FileInputStream(localFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
//sending file to stream
System.out.println("Sending...");
outToClient.write(mybytearray,0,mybytearray.length);
outToClient.flush();
outToClient.close();
}catch(Exception e){
System.out.println(e);
}
}
}
, 각 서버가 얻을 요청과 함께, 그것은 새 스레드를 생성합니다. 각 스레드는 특정 요청과 연관됩니다. 내 문제는 파일 (예 : index.html)을 요청할 때 서버가 요청을 받지만 파일이로드되지 않으면 브라우저가 계속로드됩니다.
나는 각 스레드가 시작되었지만 완료되지 않는다는 것을 알아 냈습니다.
Waiting...
Accepted connection : Socket[addr=/192.168.0.10,port=58957,localport=6790]
Waiting...
Accepted connection : Socket[addr=/192.168.0.10,port=58958,localport=6790]
Waiting...
Received: GET /html/index.html HTTP/1.1
Request Method: GET
Request URL: html/index.html
Request Protocol: HTTP/1.1
Accepted connection : Socket[addr=/192.168.0.10,port=59093,localport=6790]
Waiting...
Received: GET /index.html HTTP/1.1
Request Method: GET
Request URL: index.html
Request Protocol: HTTP/1.1
내가 뭘 잘못 여기
는 출력입니까? 더 좋은 방법이 있습니까? 하나의 IP에서만 요청을 테스트 할 단 하나의 스레드 만 수행했음을 참고하십시오.
HTTP 형식의 응답을 반환해야한다고 생각합니다. – Behnil
어떻게 완료 되었습니까? 어떤 아이디어 나 링크를 읽을 수 있습니까? – user2114721