-1
我想做一個簡單的http響應沒有太多,但它以某種方式搞砸了。它約3次連接,但有時在請求前發送第二或第三個響應,當我用Wireshark檢查它時。我很困惑大時間!Serversocket接受更多的連接,因爲它應該從同一個客戶端
下面是代碼:
public static int letThrough() throws IOException
{
ServerSocket serverSocket = new ServerSocket(80);
Socket connectionSocket = null;
while(running)
{
connectionSocket = serverSocket.accept();
System.out.println("Client: " + connectionSocket.getPort());
makeSession(connectionSocket);
}
serverSocket.close();
return 1;
}
static public Runnable makeSession(Socket connectionSocket)
{
Runnable rSession = new Runnable(){
@Override
public void run()
{
try
{
String clientIp = connectionSocket.getInetAddress().getHostAddress();
System.out.println("Client verbunden... (" + clientIp + ")");
PrintWriter oPWriter;
oPWriter = new PrintWriter(connectionSocket.getOutputStream(), false);
System.out.println("Streams erstellt...");
Date today = new Date();
Thread.sleep(10);
oPWriter.println("HTTP/1.1 200 OK");
oPWriter.println("Content-Type: text/html");
oPWriter.println("Server: Bot");
// this blank line signals the end of the headers
oPWriter.println("");
// Send the HTML page
oPWriter.println("<H1>Welcome to the Ultra Mini-WebServer</H2><br><H2>"+today.toString());
oPWriter.flush();
oPWriter.close();
connectionSocket.shutdownOutput();
while(connectionSocket.isOutputShutdown() == false)
{
Thread.sleep(100);
}
connectionSocket.close();
while(connectionSocket.isClosed() == false)
{
Thread.sleep(100);
}
}
catch (IOException | InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
new Thread(rSession).start();
return rSession;
}
我已經嘗試了一些東西,比如最後兩個while循環睡眠。任何想法我甚至可以調試這個?
您的標題是無法理解的,並且與您的問題相同。你永遠不會閱讀請求。關閉前關閉是多餘的,檢查輸出是關閉還是套接字關閉的循環是毫無意義的。刪除它們。他們永遠不會執行。 HTTP中的行結束符是'\ r \ n',而不是平臺默認值。 – EJP