socketworkerlistener.java

来自「java实现的遗传算法」· Java 代码 · 共 82 行

JAVA
82
字号
/*
 * This file is part of JGAP.
 *
 * JGAP offers a dual license model containing the LGPL as well as the MPL.
 *
 * For licencing information please see the file license.txt included with JGAP
 * or have a look at the top of class org.jgap.Chromosome which representatively
 * includes the JGAP license policy applicable for any file delivered with JGAP.
 */
package org.jgap.distr.sockets;

import org.jgap.distr.*;
import java.net.*;
import java.io.*;

/**
 * Represents a socket listener for requests from workers to the master.
 * Capable of handling multiple requests via threading
 *
 * @author Klaus Meffert
 * @since 2.4
 */
public class SocketWorkerListener
    extends WorkerListener {
  /** String containing the CVS revision. Read out via reflection!*/
  private final static String CVS_REVISION = "$Revision: 1.3 $";

  private boolean listening;

  private ServerSocket serverSocket;

  /**
   *
   * @param a_port the port to listen to
   * @param a_timeout in milliseconds
   */
  public SocketWorkerListener(int a_port, int a_timeout) {
    serverSocket = null;
    try {
      serverSocket = new ServerSocket(a_port);
      setTimeout(a_timeout);
    }
    catch (IOException ex) {
      System.err.println("Could not listen on port: " + a_port);
      ex.printStackTrace();
      System.exit( -1);
    }
  }

  public void listen()
      throws IOException {
    listening = true;
    while (listening)
      new SocketWorkerListenerThread(serverSocket.accept()).start();
    serverSocket.close();
  }

  /**
   * Sends a signal to stop the socket connection. It is not guaranteed that
   * this will happen
   */
  public void stop() {
    listening = false;
  }

  public void setTimeout(int a_milliseconds)
      throws SocketException {
    serverSocket.setSoTimeout(a_milliseconds);
  }

  /**
   * @return port to listen to
   */
  public int getPort() {
    return serverSocket.getLocalPort();
  }

  public boolean isListening() {
    return listening;
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?