【问题标题】:problem in understanding java sockets理解java套接字的问题
【发布时间】:2011-06-05 21:15:59
【问题描述】:

我在 java 中有一个应用程序,它正在扮演服务器的角色。为了限制传入连接的数量,我正在使用 ThreadPool 服务器。

但是我在理解部分代码时遇到了一些问题:

这是你的代码:


 protected ExecutorService threadPool =
        Executors.newFixedThreadPool(5);


public ThreadPooledServer(BlockingQueue queue,int port) {
    this.serverPort = port;
    this.queue=queue;

}

while (!isStopped()) {

        Socket clientSocket = null;
        try {
            System.out.println("Serverul asteapta clienti spre conectare la port" +serverPort);
            clientSocket = serverSocket.accept();
            clientconnection++;
            System.out.println("Serverul a acceptat clientul cu numarul:"
                    + clientconnection);


        } catch (IOException e) {
            if (isStopped()) {
                System.out.println("Server Stopped.");
                return;
            }
            throw new RuntimeException("Error accepting client connection",
                    e);


        }

    WorkerRunnable workerRunnable = new WorkerRunnable(queue,clientSocket);

    this.threadPool.execute(workerRunnable);

    }

    this.threadPool.shutdown();

    System.out.println("Server Stopped.");

}



private synchronized boolean isStopped() {

    return this.isStopped;

}




public synchronized void stop() {

    this.isStopped = true;

    try {

        this.serverSocket.close();

    }


    catch (IOException e) {

        throw new RuntimeException("Error closing server", e);

    }

}

private void openServerSocket() {

    try {

        InetSocketAddress serverAddr = new InetSocketAddress(SERVERIP,
                serverPort);

        serverSocket = new ServerSocket();


        serverSocket.bind(serverAddr);

    } catch (IOException e) {

        throw new RuntimeException("Cannot open port", e);

    }

}

什么我不明白:

我正在使用接受 5 个传入连接的 ThreadPooledServer....

与客户端的连接在 while() 循环中完成。

while (!isStopped()) {

}

isStopped 是此函数返回的布尔变量:

private synchronized boolean isStopped() {

    return this.isStopped;

}

我称之为启动循环的条件。

这个布尔变量最初设置为false.....然后在这里设置回true:

public synchronized void stop() {

        this.isStopped = true;

}

什么时候设置回真我的 while() 循环结束,然后我关闭我的线程池的所有工作人员。

this.threadPool.shutdown();

问题是我从不调用这个函数“stop()”

问题:当我关闭服务器时,该函数是否会自动调用??????...或者我应该在某个地方调用它????

【问题讨论】:

    标签: android multithreading


    【解决方案1】:

    您需要在代码中的某处调用它来停止服务器并关闭这些连接。如果您不这样做,系统最终将在服务器关闭时回收其资源。

    您应该能够在 JVM 中使用 register a shutdown hook(可以调用 stop())来帮助自己回收这些...祝您好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      • 2011-07-23
      相关资源
      最近更新 更多