JAVA套接字被调用太多次

时间:2018-11-02 10:48:15

标签: java sockets socketserver

我正在尝试实现ServerSocket,但我根本无法理解如果关闭连接,为什么代码会被调用3次。这是我的代码:

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import static java.lang.System.out;

public class Main {


    public static void main(String[] args) throws IOException {

        int port = 8080;
        ServerSocket serverSocket = new ServerSocket(port);
        out.println("Listening ..");

        while(true){
            Socket socket = serverSocket.accept();
            out.println("Connected" + socket.getLocalAddress());
            new Thread(new MultiThreadServer(socket)).start();
        }

    }
}



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

import static java.lang.System.out;

public class MultiThreadServer implements  Runnable{

    Socket clientSocket;

    MultiThreadServer(Socket clientSocket){ this.clientSocket = clientSocket;};

    @Override
    public void run() {

        try{
            out.println("inside thread");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
            String request = bufferedReader.readLine();
            out.println("request: " + request);
            bufferedReader.close();
            this.clientSocket.close(); //Without this line, the code is only called once
        }catch(IOException e){
            out.println(e);
        }

    }


}

因此,通过在clientSocket上调用close()方法将在“ while(true)”内部调用3次,而在不调用该方法的情况下,它将被调用一次。 这是带有socket.close()的日志:

Listening ..
Connected/0:0:0:0:0:0:0:1
inside thread
request: GET /tttes HTTP/1.1
Connected/0:0:0:0:0:0:0:1
inside thread
request: GET /tttes HTTP/1.1
Connected/0:0:0:0:0:0:0:1
inside thread
request: GET /tttes HTTP/1.1

这是没有socket.close()的日志:

Listening ..
Connected/0:0:0:0:0:0:0:1
inside thread
request: GET /tttes HTTP/1.1

1 个答案:

答案 0 :(得分:0)

您的客户端更有可能正在等待来自服务器的数据,并且在先前的连接关闭之前不会尝试再次连接。这可以解释您看到的行为。

如果您有多个并发客户端,则一个连接不知道您不会为不相关的连接关闭该连接。