Serversocket接受来自同一客户端的更多连接

时间:2016-06-08 20:15:33

标签: java sockets httpresponse

我想做一个简单的http响应,但它却以某种方式搞砸了。它提供了大约3个连接,但有时在请求之前发送第2或第3个响应,当我使用Wireshark进行检查时。我很困惑大时间!

以下是代码:

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循环。任何想法我怎么可以调试这个?

1 个答案:

答案 0 :(得分:-1)

发现问题!我的代码没有真正的问题,它是愚蠢的chrome浏览器在不使用它们的情况下建立连接。或者也许用于我无法看到的秘密事物。