private void server() {
    new CountDown(60).start();
    while (true) {
      try {
        Socket socket = serverSock.accept();
        System.out.println("New Client:" + socket);
        if (readyState[6] == 1) {
          System.out.println("正在游戏中,无法加入");
          continue;
        }
        for (i = 0; i <= 5; i++) {
          if (players[i].equals("虚位以待")) break;
        }
        if (i > 5) {
          System.out.println("房间已满,无法加入");
          continue;
        }
        i++;
        ObjectOutputStream remoteOut = new ObjectOutputStream(socket.getOutputStream());
        clients.addElement(remoteOut);

        ObjectInputStream remoteIn = new ObjectInputStream(socket.getInputStream());
        new ServerHelder(remoteIn, remoteOut, socket.getPort(), i).start();
      } catch (IOException e) {
        System.out.println(e.getMessage() + ": Failed to connect to client.");
        try {
          serverSock.close();
        } catch (IOException x) {
          System.out.println(e.getMessage() + ": Failed to close server socket.");
        }
      }
    }
  }
Exemplo n.º 2
0
  private void setSocketParameters(Socket client_sock) throws SocketException {
    if (log.isTraceEnabled())
      log.trace(
          "["
              + local_addr
              + "] accepted connection from "
              + client_sock.getInetAddress()
              + ":"
              + client_sock.getPort());
    try {
      client_sock.setSendBufferSize(send_buf_size);
    } catch (IllegalArgumentException ex) {
      if (log.isErrorEnabled())
        log.error("exception setting send buffer size to " + send_buf_size + " bytes", ex);
    }
    try {
      client_sock.setReceiveBufferSize(recv_buf_size);
    } catch (IllegalArgumentException ex) {
      if (log.isErrorEnabled())
        log.error("exception setting receive buffer size to " + send_buf_size + " bytes", ex);
    }

    client_sock.setKeepAlive(true);
    client_sock.setTcpNoDelay(tcp_nodelay);
    if (linger > 0) client_sock.setSoLinger(true, linger);
    else client_sock.setSoLinger(false, -1);
  }
Exemplo n.º 3
0
    public String toString() {
      StringBuilder ret = new StringBuilder();
      InetAddress local = null, remote = null;
      String local_str, remote_str;

      Socket tmp_sock = sock;
      if (tmp_sock == null) ret.append("<null socket>");
      else {
        // since the sock variable gets set to null we want to make
        // make sure we make it through here without a nullpointer exception
        local = tmp_sock.getLocalAddress();
        remote = tmp_sock.getInetAddress();
        local_str = local != null ? Util.shortName(local) : "<null>";
        remote_str = remote != null ? Util.shortName(remote) : "<null>";
        ret.append(
            '<'
                + local_str
                + ':'
                + tmp_sock.getLocalPort()
                + " --> "
                + remote_str
                + ':'
                + tmp_sock.getPort()
                + "> ("
                + ((System.currentTimeMillis() - last_access) / 1000)
                + " secs old)");
      }
      tmp_sock = null;

      return ret.toString();
    }
 /** @param args the command line arguments */
 public static void main(String[] args) throws Exception {
   try {
     conf = new JsonFile("config.json").read();
     address = conf.getJson().get("bind_IP").toString();
     port = Integer.parseInt(conf.getJson().get("port").toString());
     collection = new CollectThread(conf);
     collection.start();
     s = new ServerSocket(port, 50, InetAddress.getByName(address));
     System.out.print("(" + new GregorianCalendar().getTime() + ") -> ");
     System.out.print("listening on: " + address + ":" + port + "\n");
   } catch (Exception e) {
     System.out.print("(" + new GregorianCalendar().getTime() + ") -> ");
     System.out.print("error: " + e);
   }
   while (true) {
     try {
       sock = s.accept();
       System.out.print("(" + new GregorianCalendar().getTime() + ") -> ");
       System.out.print("connection from " + sock.getInetAddress() + ":");
       System.out.print(sock.getPort() + "\n");
       server = new ConsoleThread(conf, sock);
       server.start();
     } catch (Exception e) {
       System.out.print("(" + new GregorianCalendar().getTime() + ") -> ");
       System.out.print("error: " + e);
       continue;
     }
   }
 }
Exemplo n.º 5
0
  public static void main(String[] args) throws IOException {
    int servPort = Integer.parseInt(args[0]);
    ServerSocket servSock = new ServerSocket(8080); // cria o socket servidor

    int recvMsgSize; // tamanho da msg
    byte[] byteBuffer = new byte[BufSize]; // buffer de recebimento

    for (; ; ) {
      // espera as solicitações dos clientes
      Socket clntSock = servSock.accept(); // server aceita a conexão
      // imprimi o ip e a porta do servidor
      System.out.println(
          "Controlando o cliente"
              + clntSock.getInetAddress().getHostAddress()
              + "na porta"
              + clntSock.getPort());

      InputStream in = clntSock.getInputStream();
      OutputStream out = clntSock.getOutputStream();

      while ((recvMsgSize = in.read(byteBuffer))
          != -1) // lê a msg a ser transmitida até estourar o tamanho
      out.write(byteBuffer, 0, recvMsgSize);
      clntSock.close(); // fecha o socket do cliente
    }
  }
Exemplo n.º 6
0
  public boolean start() {
    try {
      socket = new Socket(server, port);
    } catch (Exception ec) {
      display("Error connectiong to server:" + ec);
      return false;
    }
    String msg = "Connection accepted " + socket.getInetAddress() + ":" + socket.getPort();
    display(msg);
    try {
      sInput = new ObjectInputStream(socket.getInputStream());
      sOutput = new ObjectOutputStream(socket.getOutputStream());
    } catch (IOException eIO) {
      display("Exception creating new Input/output Streams: " + eIO);
      return false;
    }
    new ListenFromServer().start();
    try {
      sOutput.writeObject(username);
    } catch (IOException eIO) {
      display("Exception doing login : " + eIO);
      disconnect();
      return false;
    }

    return true;
  }
Exemplo n.º 7
0
 public void startServer() throws Exception {
   while (true) {
     Socket s = server.accept();
     cClient.add(new ClientConn(s));
     ta.append("NEW-CLIENT " + s.getInetAddress() + ":" + s.getPort());
     ta.append("\n" + "CLIENTS-COUNT: " + cClient.size() + "\n\n");
   }
 }
Exemplo n.º 8
0
 private String getSockAddress() {
   StringBuilder sb = new StringBuilder();
   if (sock != null) {
     sb.append(sock.getLocalAddress().getHostAddress()).append(':').append(sock.getLocalPort());
     sb.append(" - ")
         .append(sock.getInetAddress().getHostAddress())
         .append(':')
         .append(sock.getPort());
   }
   return sb.toString();
 }
Exemplo n.º 9
0
  /**
   * Constructor for the Receiver. The passed socket is already functional.
   *
   * @param w NetworkWorld
   * @param n name of the socket
   * @param sock socket
   */
  public Receiver(NetworkWorld w, SocketName n, Socket sock) {
    super("ChatReceiver-" + sock.getInetAddress() + ":" + sock.getPort());
    world = w;
    name = n;
    socket = sock;

    try {
      input = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    } catch (IOException e) {
      e.printStackTrace();
    }

    start();
  }
Exemplo n.º 10
0
  public static void main(String[] args) {
    String ipv4;
    try {
      System.out.println("Stablishing the server socket...");
      ServerSocket srvSock = new ServerSocket(4201);
      System.out.println(
          "Server socket stablished to "
              + srvSock.getInetAddress().getHostName()
              + " at port number "
              + srvSock.getLocalPort()
              + ".\n");

      try {
        Socket comSock = srvSock.accept();
        System.out.println(
            "New connection stablished with "
                + comSock.getInetAddress().getHostName()
                + " (port "
                + comSock.getPort()
                + "), trying to communicate...");
        // DO STUFF
        try {
          BufferedReader br = new BufferedReader(new InputStreamReader(comSock.getInputStream()));
          ipv4 = br.readLine();
          br.close();
          comSock.close();
          srvSock.close();
          Socket sock = new Socket(ipv4, 4202);
          BufferedReader br2 = new BufferedReader(new InputStreamReader(sock.getInputStream()));
          System.out.println(br2.readLine());
          br2.close();
          sock.close();
          // System.out.println(ipv4);
        } catch (Exception e) {
          e.printStackTrace();
          System.out.println("Connection failed. Try again later.");
        }

      } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Problem with client.\n");
      }

    } catch (Exception e) {
      System.out.println("Failed to create server socket:");
      e.printStackTrace();
    }
  }
Exemplo n.º 11
0
 public String toString() {
   Socket tmp_sock = sock;
   if (tmp_sock == null) return "<null socket>";
   InetAddress local = tmp_sock.getLocalAddress(), remote = tmp_sock.getInetAddress();
   String local_str = local != null ? Util.shortName(local) : "<null>";
   String remote_str = remote != null ? Util.shortName(remote) : "<null>";
   return String.format(
       "%s:%s --> %s:%s (%d secs old) [%s] [recv_buf=%d]",
       local_str,
       tmp_sock.getLocalPort(),
       remote_str,
       tmp_sock.getPort(),
       TimeUnit.SECONDS.convert(getTimestamp() - last_access, TimeUnit.NANOSECONDS),
       status(),
       receiver != null ? receiver.bufferSize() : 0);
 }
Exemplo n.º 12
0
  /**
   * Creates a network access point.
   *
   * @param socket the socket that this access point is supposed to use for communication.
   * @param messageQueue the FIFO list where incoming messages should be queued
   * @param errorHandler the instance to notify when errors occur.
   */
  protected Connector(
      IceSocketWrapper socket, MessageQueue messageQueue, ErrorHandler errorHandler) {
    this.sock = socket;
    this.messageQueue = messageQueue;
    this.errorHandler = errorHandler;

    Transport transport = socket.getUDPSocket() != null ? Transport.UDP : Transport.TCP;

    listenAddress =
        new TransportAddress(socket.getLocalAddress(), socket.getLocalPort(), transport);
    if (transport == Transport.UDP) {
      remoteAddress = null;
    } else {
      Socket tcpSocket = socket.getTCPSocket();

      remoteAddress =
          new TransportAddress(tcpSocket.getInetAddress(), tcpSocket.getPort(), transport);
    }
  }
Exemplo n.º 13
0
    /**
     * Reads the peer's address. First a cookie has to be sent which has to match my own cookie,
     * otherwise the connection will be refused
     */
    private Address readPeerAddress(Socket client_sock) throws Exception {
      int timeout = client_sock.getSoTimeout();
      client_sock.setSoTimeout(peer_addr_read_timeout);

      try {
        // read the cookie first
        byte[] input_cookie = new byte[cookie.length];
        in.readFully(input_cookie, 0, input_cookie.length);
        if (!matchCookie(input_cookie))
          throw new SocketException(
              "ConnectionMap.Connection.readPeerAddress(): cookie read by "
                  + getLocalAddress()
                  + " does not match own cookie; terminating connection");
        // then read the version
        short version = in.readShort();

        if (!Version.isBinaryCompatible(version)) {
          if (log.isWarnEnabled())
            log.warn(
                new StringBuilder("packet from ")
                    .append(client_sock.getInetAddress())
                    .append(':')
                    .append(client_sock.getPort())
                    .append(" has different version (")
                    .append(Version.print(version))
                    .append(") from ours (")
                    .append(Version.printVersion())
                    .append("). This may cause problems")
                    .toString());
        }
        Address client_peer_addr = new IpAddress();
        client_peer_addr.readFrom(in);

        updateLastAccessed();
        return client_peer_addr;
      } finally {
        client_sock.setSoTimeout(timeout);
      }
    }
Exemplo n.º 14
0
  /**
   * Reads the peer's address. First a cookie has to be sent which has to match my own cookie,
   * otherwise the connection will be refused
   */
  protected Address readPeerAddress(Socket client_sock) throws Exception {
    int timeout = client_sock.getSoTimeout();
    client_sock.setSoTimeout(server.peerAddressReadTimeout());

    try {
      // read the cookie first
      byte[] input_cookie = new byte[cookie.length];
      in.readFully(input_cookie, 0, input_cookie.length);
      if (!Arrays.equals(cookie, input_cookie))
        throw new SocketException(
            "BaseServer.TcpConnection.readPeerAddress(): cookie read by "
                + server.localAddress()
                + " does not match own cookie; terminating connection");
      // then read the version
      short version = in.readShort();
      if (!Version.isBinaryCompatible(version))
        throw new IOException(
            "packet from "
                + client_sock.getInetAddress()
                + ":"
                + client_sock.getPort()
                + " has different version ("
                + Version.print(version)
                + ") from ours ("
                + Version.printVersion()
                + "); discarding it");
      short addr_len = in.readShort(); // only needed by NioConnection

      Address client_peer_addr = new IpAddress();
      client_peer_addr.readFrom(in);
      updateLastAccessed();
      return client_peer_addr;
    } finally {
      client_sock.setSoTimeout(timeout);
    }
  }
Exemplo n.º 15
0
  public static void main(String args[]) {

    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    int bytesRead;
    int current = 0;
    int varInc = 0; // A decrementer pour simuler la perte de la meme trame pour son deuxiem envoi

    int port = 1500;
    ServerSocket socket_serveur;
    BufferedReader input;
    PrintWriter out; // Ajouté

    System.out.println("\n\n*********************************");
    System.out.println("***********Serveur***************");
    System.out.println("*********************************\n\n");
    // si le port est donne en argument!!
    if (args.length == 1) {
      try {
        port = Integer.parseInt(args[0]);
      } catch (Exception e) {
        System.out.println("port d'ecoute= 1500 (par defaut)");
        port = 1500;
      }
    }

    // Ouverture du socket en attente de connexions
    try {
      socket_serveur = new ServerSocket(port);
      System.out.println(
          "Serveur en attente de clients sur le port " + socket_serveur.getLocalPort());

      // boucle infinie: traitement d'une connexion client
      while (true) {
        Socket socket = socket_serveur.accept();
        System.out.println(
            "nouvelle connexion acceptee " + socket.getInetAddress() + ":" + socket.getPort());
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        /*
         *
         * Reception des Trames envoyées par le client 1 Rassembler le
         * tout dans un tableau
         */

        ArrayList<Tram> listTrames = new ArrayList<Tram>();
        try {
          ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
          ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
          Tram trame;
          Tram ack;

          while ((trame = (Tram) ois.readObject()) != null) {
            System.out.print(
                "trame n° "
                    + trame.id
                    + " du fichier : "
                    + FILE_TO_RECEIVED
                    + " telechargée  ("
                    + trame.tabOct.length
                    + "bytes read)");

            if (!listTrames.isEmpty()) { // si ce n'est pas la premiere trame
              if (listTrames.get(listTrames.size() - 1).id
                  == trame.id - 1) { // si c'est la trame qui suit celle recue prealabment
                System.out.println(" <= Données acceptées ");
                listTrames.add(trame);

              } else {
                System.out.println(" <= Données refusées ");
              }

            } else {
              if (trame.id == 0) {
                System.out.println(" <= Données acceptées ");
                listTrames.add(trame);
              } else {
                System.out.println(" <= Données refusées ");
              }
            }

            // Données acceptées ou refusées il faut envoyer un ACK !!!

            // envoie ACK //
            ack = new Tram(null, trame.id); // Envoi une trame vide
            // de 0 octets mais avec
            // l'id de la trame
            // d'avant
            Timer timer = new Timer();
            if (ack.id == 2 && varInc == 0) {
              varInc++;

            } else {
              oos.writeObject(ack);
              System.out.println("Envoi de l'ack pour la trame " + trame.id);
            }

            if (trame.id == 8) break; // le break est a refaire dynamiquement

            oos.flush();
          }

        } catch (ClassNotFoundException e1) {
          // TODO Auto-generated catch block
          e1.printStackTrace();
        }

        /*
         * ETAPE 2 : parcourir le tableau contenant les trames pour les
         * rasesmbler
         */

        System.out.println("Etap 2 ");

        fos = new FileOutputStream(FILE_TO_RECEIVED);
        bos = new BufferedOutputStream(fos);

        for (Tram trame : listTrames) {

          bos.write(trame.tabOct, 0, trame.tabOct.length); // ecrire
          // les 5
          // bytes
          // de la
          // trame
          // i (
          // ou
          // moins
          // pour
          // la
          // derniere)
          // dans
          // bos
          bos.flush();
        }

        // connexion fermee par client
        try {
          socket.close();
          System.out.println("connexion fermee par le client");
        } catch (IOException e) {
          System.out.println(e);
        }
      }

    } catch (IOException e) {
      System.out.println(e);
    }
  }
Exemplo n.º 16
0
 public Socket4 openParallelSocket() throws IOException {
   if (_hostName == null) {
     throw new IllegalStateException();
   }
   return createParallelSocket(_hostName, _socket.getPort());
 }
Exemplo n.º 17
0
    private void saveDataIntoDB(String data) throws SQLException {
      try {
        data = data.replaceAll("\n", "");
        data = data.replaceAll("\r", "");

        String[] item = data.split(",");

        String LocID = item[0];
        String Longitude = item[1];
        String Latitude = item[2];
        String Altitude = item[3];
        String Speed = item[4];
        String Course = item[5];
        String TrueTime = item[6];
        String EventID = item[7];

        if (item[1].trim().contains("0.0")) {
          String[] coords = getLastCoords(LocID);
          Longitude = coords[0];
          Latitude = coords[1];
        }

        String Location = getAddressXY(Longitude, Latitude);
        String IPAddress = clientConnection.getInetAddress().getHostAddress();
        String IPPort = clientConnection.getPort() + "";

        if ("NaN".equalsIgnoreCase(Altitude)) Altitude = "0.0";
        if ("NaN".equalsIgnoreCase(Speed)) Speed = "0.0";
        if ("NaN".equalsIgnoreCase(Course)) Course = "0.0";

        Statement comm = conn.createStatement();

        String sql =
            "INSERT INTO ZZZ_BLACKBERRY ("
                + "LocID,"
                + "Longitude,"
                + "Latitude,"
                + "Altitude,"
                + "Speed,"
                + "Course,"
                + "TrueTime,"
                + "EventID,"
                + "Location,"
                + "IPAddress,"
                + "IPPort"
                + ") "
                + "VALUES ("
                + "'"
                + LocID
                + "',"
                + Longitude
                + ","
                + Latitude
                + ","
                + Altitude
                + ","
                + Speed
                + ","
                + Course
                + ","
                + "'"
                + TrueTime
                + "',"
                + "'"
                + EventID
                + "',"
                + "'"
                + Location
                + "',"
                + "'"
                + IPAddress
                + "',"
                + IPPort
                + ")";

        comm.execute(sql);
        comm.close();

        windowServer.model.setValueAt("LocID", 0, 0);
        windowServer.model.setValueAt(LocID, 0, 1);
        windowServer.model.setValueAt("Longitude", 1, 0);
        windowServer.model.setValueAt(Longitude, 1, 1);
        windowServer.model.setValueAt("Latitude", 2, 0);
        windowServer.model.setValueAt(Latitude, 2, 1);
        windowServer.model.setValueAt("Altitude", 3, 0);
        windowServer.model.setValueAt(Altitude, 3, 1);
        windowServer.model.setValueAt("Speed", 4, 0);
        windowServer.model.setValueAt(Speed, 4, 1);
        windowServer.model.setValueAt("Course", 5, 0);
        windowServer.model.setValueAt(Course, 5, 1);
        windowServer.model.setValueAt("TrueTime", 6, 0);
        windowServer.model.setValueAt(TrueTime, 6, 1);
        windowServer.model.setValueAt("EventID", 7, 0);
        windowServer.model.setValueAt(EventID, 7, 1);
        windowServer.model.setValueAt("Location", 8, 0);
        windowServer.model.setValueAt(Location, 8, 1);
        windowServer.model.setValueAt("IPAddress", 9, 0);
        windowServer.model.setValueAt(IPAddress, 9, 1);
        windowServer.model.setValueAt("IPPort", 10, 0);
        windowServer.model.setValueAt(IPPort, 10, 1);
        windowServer.model.fireTableDataChanged();

        String fileName = LocID + "_" + TrueTime.substring(0, 10).replace("/", "");
        saveToFile(data, fileName);

      } catch (SQLException e) {
        windowServer.txtErrors.append(e.getMessage() + "\n");

      } catch (Exception e) {
        windowServer.txtErrors.append(e.getMessage() + "\n");
      }
    }
Exemplo n.º 18
0
 public static void main(String[] args) {
   // Initialize the logger (saves to RMG.log file).
   Logger.initialize();
   initializeSystemProperties();
   try {
     ChemGraph.readForbiddenStructure();
   } catch (IOException e1) {
     System.err.println("PopulateReactions cannot locate forbiddenStructures.txt file");
     e1.printStackTrace();
   }
   ArrheniusKinetics.setAUnits("moles");
   ArrheniusKinetics.setEaUnits("kcal/mol");
   // Creating a new ReactionModelGenerator so I can set the variable temp4BestKinetics
   // and call the new readAndMakePTL and readAndMakePRL methods
   ReactionModelGenerator rmg = new ReactionModelGenerator();
   rmg.setSpeciesSeed(new LinkedHashSet());
   // Set Global.lowTemp and Global.highTemp
   // The values of the low/highTemp are not used in the function
   // (to the best of my knowledge).
   // They are necessary for the instances of additionalKinetics,
   // e.g. H2C*-CH2-CH2-CH3 -> H3C-CH2-*CH-CH3
   /*
    * 7Apr2010: The input file will now ask the user for a TemperatureModel and PressureModel (same as the RMG
    * module). The Global .lowTemperature and .highTemperature will automatically be determined
    */
   // Global.lowTemperature = new Temperature(300,"K");
   // Global.highTemperature = new Temperature(1500,"K");
   // Define variable 'speciesSet' to store the species contained in the input file
   LinkedHashSet speciesSet = new LinkedHashSet();
   // Define variable 'reactions' to store all possible rxns between the species in speciesSet
   LinkedHashSet reactions = new LinkedHashSet();
   // Define two string variables 'listOfReactions' and 'listOfSpecies'
   // These strings will hold the list of rxns (including the structure,
   // modified Arrhenius parameters, and source/comments) and the list of
   // species (including the chemkin name and graph), respectively
   String listOfReactions =
       "Arrhenius 'A' parameter has units of: "
           + ArrheniusEPKinetics.getAUnits()
           + ",cm3,s\n"
           + "Arrhenius 'n' parameter is unitless and assumes Tref = 1K\n"
           + "Arrhenius 'E' parameter has units of: "
           + ArrheniusEPKinetics.getEaUnits()
           + "\n\n";
   String listOfSpecies = "";
   // Open and read the input file
   try {
     FileReader fr_input = new FileReader(args[0]);
     BufferedReader br_input = new BufferedReader(fr_input);
     // Read in the Database field
     String line = ChemParser.readMeaningfulLine(br_input, true);
     if (line.toLowerCase().startsWith("database")) {
       RMG.extractAndSetDatabasePath(line);
     } else {
       System.err.println("PopulateReactions: Could not" + " locate the Database field");
       System.exit(0);
     }
     // Read in the first line of the input file
     // This line should hold the temperature of the system, e.g.
     // Temperature: 500 (K)
     line = ChemParser.readMeaningfulLine(br_input, true);
     /*
      * Read max atom types (if they exist)
      */
     line = rmg.readMaxAtomTypes(line, br_input);
     /*
      * Read primary thermo libraries (if they exist)
      */
     if (line.toLowerCase().startsWith("primarythermolibrary")) {
       rmg.readAndMakePTL(br_input);
     } else {
       System.err.println(
           "PopulateReactions: Could not locate the PrimaryThermoLibrary field.\n"
               + "Line read was: "
               + line);
       System.exit(0);
     }
     line = ChemParser.readMeaningfulLine(br_input, true);
     // Read primary transport library
     if (line.toLowerCase().startsWith("primarytransportlibrary"))
       rmg.readAndMakePTransL(br_input);
     else {
       System.err.println(
           "PopulateReactions: Could not locate the PrimaryTransportLibrary field.\n"
               + "Line read was: "
               + line);
       System.exit(0);
     }
     /*
      * Read the temperature model (must be of length one)
      */
     line = ChemParser.readMeaningfulLine(br_input, true);
     rmg.createTModel(line);
     if (rmg.getTempList().size() > 1) {
       System.out.println("Please list only one temperature in the TemperatureModel field.");
       System.exit(0);
     }
     // Set the user's input temperature
     LinkedList tempList = rmg.getTempList();
     systemTemp = ((ConstantTM) tempList.get(0)).getTemperature();
     rmg.setTemp4BestKinetics(systemTemp);
     /*
      * Read the pressure model (must be of length 1)
      */
     line = ChemParser.readMeaningfulLine(br_input, true);
     rmg.createPModel(line);
     if (rmg.getPressList().size() > 1) {
       System.out.println("Please list only one pressure in the PressureModel field.");
       System.exit(0);
     }
     /*
      * Read the solvation field (if present)
      */
     line = ChemParser.readMeaningfulLine(br_input, true);
     StringTokenizer st = new StringTokenizer(line);
     // The first line should start with "Solvation", otherwise do nothing and display a message to
     // the user
     if (st.nextToken().startsWith("Solvation")) {
       line = st.nextToken().toLowerCase();
       // The options for the "Solvation" field are "on" or "off" (as of 18May2009), otherwise do
       // nothing and
       // display a message to the user
       // Note: I use "Species.useInChI" because the "Species.useSolvation" updates were not yet
       // committed.
       if (line.equals("on")) {
         Species.useSolvation = true;
         // rmg.setUseDiffusion(true);
         listOfReactions += "Solution-phase chemistry!\n\n";
       } else if (line.equals("off")) {
         Species.useSolvation = false;
         // rmg.setUseDiffusion(false);
         listOfReactions += "Gas-phase chemistry.\n\n";
       } else {
         System.out.println(
             "Error in reading input.txt file:\nThe field 'Solvation' has the options 'on' or 'off'."
                 + "\nPopulateReactions does not recognize: "
                 + line);
         return;
       }
       line = ChemParser.readMeaningfulLine(br_input, true);
     }
     /*
      * Read in the species (name, concentration, adjacency list)
      */
     if (line.toLowerCase().startsWith("speciesstatus")) {
       LinkedHashMap lhm = new LinkedHashMap();
       lhm = rmg.populateInitialStatusListWithReactiveSpecies(br_input);
       speciesSet.addAll(lhm.values());
     }
     /*
      * Read in the inert gas (name, concentration)
      */
     line = ChemParser.readMeaningfulLine(br_input, true);
     if (line.toLowerCase().startsWith("bathgas")) {
       rmg.populateInitialStatusListWithInertSpecies(br_input);
     }
     /*
      * Read in the p-dep options
      */
     line = ChemParser.readMeaningfulLine(br_input, true);
     if (line.toLowerCase().startsWith("spectroscopicdata")) {
       rmg.setSpectroscopicDataMode(line);
       line = ChemParser.readMeaningfulLine(br_input, true);
       line = rmg.setPressureDependenceOptions(line, br_input);
     }
     /*
      * Read primary kinetic libraries (if they exist)
      */
     if (line.toLowerCase().startsWith("primarykineticlibrary")) {
       rmg.readAndMakePKL(br_input);
     } else {
       System.err.println(
           "PopulateReactions: Could not locate the PrimaryKineticLibrary field."
               + "Line read was: "
               + line);
       System.exit(0);
     }
     line = ChemParser.readMeaningfulLine(br_input, true);
     if (line.toLowerCase().startsWith("reactionlibrary")) {
       rmg.readAndMakeReactionLibrary(br_input);
     } else {
       System.err.println(
           "PopulateReactions: Could not locate the ReactionLibrary field."
               + "Line read was: "
               + line);
       System.exit(0);
     }
     /*
      * Read in verbosity field (if it exists)
      */
     line = ChemParser.readMeaningfulLine(br_input, true);
     if (line != null && line.toLowerCase().startsWith("verbose")) {
       StringTokenizer st2 = new StringTokenizer(line);
       String tempString = st2.nextToken();
       tempString = st2.nextToken();
       tempString = tempString.toLowerCase();
       if (tempString.equals("on") || tempString.equals("true") || tempString.equals("yes"))
         ArrheniusKinetics.setVerbose(true);
     }
     TemplateReactionGenerator rtLibrary = new TemplateReactionGenerator();
     // / THE SERVERY BIT
     ServerSocket Server = new ServerSocket(5000);
     Logger.info("TCPServer Waiting for client on port 5000");
     Logger.info("Switching to quiet mode - only WARNINGS and above will be logged...");
     Logger.setConsoleLevel(jing.rxnSys.Logger.WARNING);
     Logger.setFileLevel(jing.rxnSys.Logger.WARNING);
     while (true) {
       Socket connected = Server.accept();
       Logger.warning(
           " THE CLIENT"
               + " "
               + connected.getInetAddress()
               + ":"
               + connected.getPort()
               + " IS CONNECTED ");
       BufferedReader inFromClient =
           new BufferedReader(new InputStreamReader(connected.getInputStream()));
       inFromClient.mark(4096); // so you can reset up to 4096 characters back.
       PrintWriter outToClient = new PrintWriter(connected.getOutputStream(), true);
       try {
         listOfReactions =
             "Arrhenius 'A' parameter has units of: "
                 + ArrheniusEPKinetics.getAUnits()
                 + ",cm3,s\n"
                 + "Arrhenius 'n' parameter is unitless and assumes Tref = 1K\n"
                 + "Arrhenius 'E' parameter has units of: "
                 + ArrheniusEPKinetics.getEaUnits()
                 + "\n\n";
         listOfSpecies = "";
         // clear old things
         speciesSet.clear();
         reactions.clear();
         /*
          * Read in the species (name, concentration, adjacency list)
          */
         LinkedHashMap lhm = new LinkedHashMap();
         lhm = rmg.populateInitialStatusListWithReactiveSpecies(inFromClient);
         speciesSet.addAll(lhm.values());
         // Check Reaction Library
         ReactionLibrary RL = rmg.getReactionLibrary();
         LibraryReactionGenerator lrg1 = new LibraryReactionGenerator(RL);
         reactions = lrg1.react(speciesSet);
         if (RL != null) {
           System.out.println("Checking Reaction Library " + RL.getName() + " for reactions.");
           Iterator ReactionIter = reactions.iterator();
           while (ReactionIter.hasNext()) {
             Reaction current_reaction = (Reaction) ReactionIter.next();
             System.out.println("Library Reaction: " + current_reaction.toString());
           }
         }
         // Add all reactions found from RMG template reaction generator
         reactions.addAll(rtLibrary.react(speciesSet));
         System.out.println("FINISHED generating template reactions");
         if (!(rmg.getReactionModelEnlarger() instanceof RateBasedRME)) {
           // NOT an instance of RateBasedRME therefore assume RateBasedPDepRME and we're doing
           // pressure
           // dependence
           CoreEdgeReactionModel cerm = new CoreEdgeReactionModel(speciesSet, reactions);
           rmg.setReactionModel(cerm);
           rmg.setReactionGenerator(rtLibrary);
           ReactionSystem rs =
               new ReactionSystem(
                   (TemperatureModel) rmg.getTempList().get(0),
                   (PressureModel) rmg.getPressList().get(0),
                   rmg.getReactionModelEnlarger(),
                   new FinishController(),
                   null,
                   rmg.getPrimaryKineticLibrary(),
                   rmg.getReactionGenerator(),
                   speciesSet,
                   (InitialStatus) rmg.getInitialStatusList().get(0),
                   rmg.getReactionModel(),
                   rmg.getLibraryReactionGenerator(),
                   0,
                   "GasPhase");
           PDepNetwork.reactionModel = rmg.getReactionModel();
           PDepNetwork.reactionSystem = rs;
           // If the reaction structure is A + B = C + D, we are not concerned w/pdep
           Iterator iter = reactions.iterator();
           LinkedHashSet nonPdepReactions = new LinkedHashSet();
           while (iter.hasNext()) {
             Reaction r = (Reaction) iter.next();
             if (FastMasterEqn.isReactionPressureDependent(r)) {
               cerm.categorizeReaction(r.getStructure());
               PDepNetwork.addReactionToNetworks(r);
             } else {
               nonPdepReactions.add(r);
             }
           }
           // Run fame calculation
           PDepKineticsEstimator pDepKineticsEstimator =
               ((RateBasedPDepRME) rmg.getReactionModelEnlarger()).getPDepKineticsEstimator();
           BathGas bathGas = new BathGas(rs);
           for (int numNetworks = 0;
               numNetworks < PDepNetwork.getNetworks().size();
               ++numNetworks) {
             LinkedHashSet allSpeciesInNetwork = new LinkedHashSet();
             PDepNetwork pdepnetwork = PDepNetwork.getNetworks().get(numNetworks);
             LinkedList isomers = pdepnetwork.getIsomers();
             for (int numIsomers = 0; numIsomers < isomers.size(); ++numIsomers) {
               PDepIsomer currentIsomer = (PDepIsomer) isomers.get(numIsomers);
               if (currentIsomer.getNumSpecies() == 2)
                 pdepnetwork.makeIsomerIncluded(currentIsomer);
             }
             pDepKineticsEstimator.runPDepCalculation(pdepnetwork, rs, cerm);
             if (pdepnetwork.getNetReactions().size() > 0) {
               String formatSpeciesName = "%1$-16s\t";
               listOfReactions +=
                   "!PDepNetwork\n"
                       + "!\tdeltaEdown = "
                       + bathGas.getDeltaEdown().getAlpha()
                       + "(T / "
                       + bathGas.getDeltaEdown().getT0()
                       + ")^"
                       + bathGas.getDeltaEdown().getN()
                       + " kJ/mol\n"
                       + "!\tbathgas MW = "
                       + bathGas.getMolecularWeight()
                       + " amu\n"
                       + "!\tbathgas LJ sigma = "
                       + bathGas.getLJSigma()
                       + " meters\n"
                       + "!\tbathgas LJ epsilon = "
                       + bathGas.getLJEpsilon()
                       + " Joules\n"
                       + "!Here are the species and their thermochemistry:\n";
               LinkedList<PDepIsomer> allpdepisomers = pdepnetwork.getIsomers();
               for (int numIsomers = 0; numIsomers < allpdepisomers.size(); ++numIsomers) {
                 LinkedList species = allpdepisomers.get(numIsomers).getSpeciesList();
                 for (int numSpecies = 0; numSpecies < species.size(); ++numSpecies) {
                   Species currentSpec = (Species) species.get(numSpecies);
                   if (!allSpeciesInNetwork.contains(currentSpec)) {
                     listOfReactions +=
                         "!\t"
                             + String.format(formatSpeciesName, currentSpec.getFullName())
                             + currentSpec.getThermoData().toString()
                             + currentSpec.getThermoData().getSource()
                             + "\n";
                     allSpeciesInNetwork.add(currentSpec);
                   }
                 }
                 speciesSet.addAll(species);
               }
               String formatRxnName = "%1$-32s\t";
               listOfReactions +=
                   "!Here are the path reactions and their high-P limit kinetics:\n";
               LinkedList<PDepReaction> pathRxns = pdepnetwork.getPathReactions();
               for (int numPathRxns = 0; numPathRxns < pathRxns.size(); numPathRxns++) {
                 Kinetics[] currentKinetics = pathRxns.get(numPathRxns).getKinetics();
                 for (int numKinetics = 0; numKinetics < currentKinetics.length; ++numKinetics) {
                   listOfReactions +=
                       "!\t"
                           + String.format(
                               formatRxnName,
                               pathRxns.get(numPathRxns).getStructure().toRestartString(true))
                           + currentKinetics[numKinetics].toChemkinString(
                               pathRxns
                                   .get(numPathRxns)
                                   .calculateHrxn(new Temperature(298.0, "K")),
                               new Temperature(298.0, "K"),
                               false)
                           + "\n";
                 }
               }
               listOfReactions += "\n";
               LinkedList<PDepReaction> indivPDepRxns = pdepnetwork.getNetReactions();
               for (int numPDepRxns = 0; numPDepRxns < indivPDepRxns.size(); numPDepRxns++) {
                 listOfReactions += indivPDepRxns.get(numPDepRxns).toRestartString(systemTemp);
               }
               LinkedList<PDepReaction> nonIncludedRxns = pdepnetwork.getNonincludedReactions();
               for (int numNonRxns = 0; numNonRxns < nonIncludedRxns.size(); ++numNonRxns) {
                 listOfReactions += nonIncludedRxns.get(numNonRxns).toRestartString(systemTemp);
               }
             }
           }
           reactions = nonPdepReactions;
         }
         // Some of the reactions may be duplicates of one another
         // (e.g. H+CH4=CH3+H2 as a forward reaction and reverse reaction)
         // Create new LinkedHashSet which will store the non-duplicate rxns
         LinkedHashSet nonDuplicateRxns = new LinkedHashSet();
         int Counter = 0;
         Iterator iter_rxns = reactions.iterator();
         while (iter_rxns.hasNext()) {
           ++Counter;
           Reaction r = (Reaction) iter_rxns.next();
           // The first reaction is not a duplicate of any previous reaction
           if (Counter == 1) {
             nonDuplicateRxns.add(r);
             listOfReactions += writeOutputString(r, rtLibrary);
             speciesSet.addAll(r.getProductList());
           }
           // Check whether the current reaction (or its reverse) has the same structure
           // of any reactions already reported in the output
           else {
             Iterator iterOverNonDup = nonDuplicateRxns.iterator();
             boolean dupRxn = false;
             while (iterOverNonDup.hasNext()) {
               Reaction temp_Reaction = (Reaction) iterOverNonDup.next();
               if (r.getStructure() == temp_Reaction.getStructure()) {
                 dupRxn = true;
                 break;
               } else if (r.hasReverseReaction()) {
                 if (r.getReverseReaction().getStructure() == temp_Reaction.getStructure()) {
                   dupRxn = true;
                   break;
                 }
               }
             }
             if (!dupRxn) {
               nonDuplicateRxns.add(r);
               // If Reaction is Not a Library Reaction
               listOfReactions += writeOutputString(r, rtLibrary);
               speciesSet.addAll(r.getProductList());
             }
           }
         }
         Iterator iter_species = speciesSet.iterator();
         // Define dummy integer 'i' so our getChemGraph().toString()
         // call only returns the graph
         int i = 0;
         while (iter_species.hasNext()) {
           Species species = (Species) iter_species.next();
           listOfSpecies +=
               species.getFullName() + "\n" + species.getChemGraph().toStringWithoutH(i) + "\n";
         }
         // Write the output files
         try {
           File rxns = new File("PopRxnsOutput_rxns.txt");
           FileWriter fw_rxns = new FileWriter(rxns);
           fw_rxns.write(listOfReactions);
           fw_rxns.close();
           File spcs = new File("PopRxnsOutput_spcs.txt");
           FileWriter fw_spcs = new FileWriter(spcs);
           fw_spcs.write(listOfSpecies);
           fw_spcs.close();
         } catch (IOException e) {
           System.err.println("Could not write PopRxnsOutput*.txt files");
         }
         // Display to the user that the program was successful and also
         // inform them where the results may be located
         System.out.println(
             "Reaction population complete. "
                 + "Results are stored in PopRxnsOutput_rxns.txt and PopRxnsOutput_spcs.txt");
         // send output to client
         System.out.println("SENDING RESPONSE TO CLIENT");
         outToClient.println(listOfSpecies);
         outToClient.println(listOfReactions);
       } catch (Throwable t) {
         Logger.error("Error in PopulateReactionsServer");
         try {
           inFromClient.reset();
           Logger.error("Input:");
           while (inFromClient.ready()) {
             Logger.error(inFromClient.readLine());
           }
         } catch (IOException e) {
           Logger.error("Couldn't read input stream");
         }
         Logger.logStackTrace(t);
         outToClient.println("Error in PopulateReactionsServer");
         t.printStackTrace(outToClient);
       }
       connected.close();
       System.out.println("SOCKET CLOSED");
     }
   } catch (FileNotFoundException e) {
     System.err.println("File was not found!\n");
   } catch (IOException e) {
     System.err.println(
         "IOException: Something maybe wrong with ChemParser.readChemGraph.\n" + e.toString());
   }
 }
Exemplo n.º 19
0
 @Override
 public String toString() {
   return ehost + ':' + socket.getPort();
 }
Exemplo n.º 20
0
 public int getPort() {
   return mSocket.getPort();
 }
    public void run() {
      // Here's where everything happens. The select method will
      // return when any operations registered above have occurred, the
      // thread has been interrupted, etc.
      try {
        while (!stop) {
          try {
            if (selector.select() > 0) {
              if (stop) {
                break;
              }
              // Someone is ready for I/O, get the ready keys
              Set readyKeys = selector.selectedKeys();
              Iterator it = readyKeys.iterator();

              // Walk through the ready keys collection and process date requests.
              while (it.hasNext()) {
                SelectionKey sk = (SelectionKey) it.next();
                it.remove();
                SocketChannel readChannel = null;
                TcpAddress incomingAddress = null;
                if (sk.isAcceptable()) {
                  // The key indexes into the selector so you
                  // can retrieve the socket that's ready for I/O
                  ServerSocketChannel nextReady = (ServerSocketChannel) sk.channel();
                  // Accept the date request and send back the date string
                  Socket s = nextReady.accept().socket();
                  readChannel = s.getChannel();
                  readChannel.configureBlocking(false);
                  readChannel.register(selector, SelectionKey.OP_READ);

                  incomingAddress = new TcpAddress(s.getInetAddress(), s.getPort());
                  SocketEntry entry = new SocketEntry(incomingAddress, s);
                  sockets.put(incomingAddress, entry);
                  timeoutSocket(entry);
                  TransportStateEvent e =
                      new TransportStateEvent(
                          DefaultTcpTransportMapping.this,
                          incomingAddress,
                          TransportStateEvent.STATE_CONNECTED,
                          null);
                  fireConnectionStateChanged(e);
                } else if (sk.isReadable()) {
                  readChannel = (SocketChannel) sk.channel();
                  incomingAddress =
                      new TcpAddress(
                          readChannel.socket().getInetAddress(), readChannel.socket().getPort());
                } else if (sk.isWritable()) {
                  try {
                    SocketEntry entry = (SocketEntry) sk.attachment();
                    SocketChannel sc = (SocketChannel) sk.channel();
                    if (entry != null) {
                      writeMessage(entry, sc);
                    }
                  } catch (IOException iox) {
                    if (logger.isDebugEnabled()) {
                      iox.printStackTrace();
                    }
                    logger.warn(iox);
                    TransportStateEvent e =
                        new TransportStateEvent(
                            DefaultTcpTransportMapping.this,
                            incomingAddress,
                            TransportStateEvent.STATE_DISCONNECTED_REMOTELY,
                            iox);
                    fireConnectionStateChanged(e);
                    sk.cancel();
                  }
                } else if (sk.isConnectable()) {
                  try {
                    SocketEntry entry = (SocketEntry) sk.attachment();
                    SocketChannel sc = (SocketChannel) sk.channel();
                    if ((!sc.isConnected()) && (sc.finishConnect())) {
                      sc.configureBlocking(false);
                      logger.debug("Connected to " + entry.getPeerAddress());
                      // make sure conncetion is closed if not used for timeout
                      // micro seconds
                      timeoutSocket(entry);
                      sc.register(selector, SelectionKey.OP_WRITE, entry);
                    }
                    TransportStateEvent e =
                        new TransportStateEvent(
                            DefaultTcpTransportMapping.this,
                            incomingAddress,
                            TransportStateEvent.STATE_CONNECTED,
                            null);
                    fireConnectionStateChanged(e);
                  } catch (IOException iox) {
                    if (logger.isDebugEnabled()) {
                      iox.printStackTrace();
                    }
                    logger.warn(iox);
                    sk.cancel();
                  }
                }

                if (readChannel != null) {
                  try {
                    readMessage(sk, readChannel, incomingAddress);
                  } catch (IOException iox) {
                    // IO exception -> channel closed remotely
                    if (logger.isDebugEnabled()) {
                      iox.printStackTrace();
                    }
                    logger.warn(iox);
                    sk.cancel();
                    readChannel.close();
                    TransportStateEvent e =
                        new TransportStateEvent(
                            DefaultTcpTransportMapping.this,
                            incomingAddress,
                            TransportStateEvent.STATE_DISCONNECTED_REMOTELY,
                            iox);
                    fireConnectionStateChanged(e);
                  }
                }
              }
            }
          } catch (NullPointerException npex) {
            // There seems to happen a NullPointerException within the select()
            npex.printStackTrace();
            logger.warn("NullPointerException within select()?");
          }
          processPending();
        }
        if (ssc != null) {
          ssc.close();
        }
      } catch (IOException iox) {
        logger.error(iox);
        lastError = iox;
      }
      if (!stop) {
        stop = true;
        synchronized (DefaultTcpTransportMapping.this) {
          server = null;
        }
      }
    }
Exemplo n.º 22
0
 public InetSocketAddress getRemoteAddress() {
   Socket s = connection.getChannel().socket();
   InetAddress ia = s.getInetAddress();
   int port = s.getPort();
   return new InetSocketAddress(ia, port);
 }
Exemplo n.º 23
0
  public void listenSocket() {
    // Create socket connection
    ObjectInputStream ois = null;
    ObjectOutputStream oos = null;
    Date date = null;
    int[][] gridd = new int[9][9];
    boolean[][] fieldsDefault = new boolean[9][9];

    try {
      socket = new Socket("localhost", 12340);
      System.out.println(
          "Connected to"
              + socket.getInetAddress()
              + " on port "
              + socket.getPort()
              + "from port "
              + socket.getLocalPort()
              + " of "
              + socket.getLocalAddress());

      oos = new ObjectOutputStream(socket.getOutputStream());
      ois = new ObjectInputStream(socket.getInputStream());
      // read an object from the server
      // System.out.println("Before reading the object");
      // date = (Date) ois.readObject();

      System.out.println("Before reading the object");

      gridd = (int[][]) ois.readObject();
      fieldsDefault = (boolean[][]) ois.readObject();
      System.out.println("After reading the object");

      for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
          System.out.println(gridd[i][j] + " |");
        }
        System.out.println("\n");
      }
      for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
          System.out.println("**************************" + fieldsDefault[i][j] + " |");
        }
        System.out.println("\n");
      }

      gg.getGrid().resetGrid();
      gg.getGrid().setFieldss(gridd);
      // System.out.print("The date is: " + date);
      System.out.println("Blah Blah");

      //	oos.close();
      //	ois.close();
    } catch (Exception e) {
      System.out.println(e);
    }

    // ----------------------------------------------------------------------------------------------------------------
    try {
      out = new PrintWriter(socket.getOutputStream(), true);

      in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    } catch (UnknownHostException e) {
      System.out.println("Unknown host: kq6py.eng");
      System.exit(1);
    } catch (IOException e) {
      System.out.println("No I/O" + e);
      System.exit(1);
    }

    int i = -1;
    while (i == -1) {
      try {
        String line = in.readLine();
        /*System.out.println("Line is  :  "+ line);
        System.out
        .println("Connected to" + socket.getInetAddress()
        		+ " on port " + socket.getPort() + "from port "
        		+ socket.getLocalPort() + " of "
        		+ socket.getLocalAddress());
        		*/
        // if (line.length() > 0)
        if (line != null) {
          System.out.println("Someone else won!!!");
          doOtherPersonWon();
          i = 0;
        }

      } catch (IOException e) {
        System.out.println("Read failed");
        System.exit(1);
      }
    }
  }
Exemplo n.º 24
0
 public ChatServerThread(ChatServer _server, Socket _socket) {
   super();
   server = _server;
   socket = _socket;
   ID = socket.getPort();
 }
Exemplo n.º 25
0
 /**
  * Returns a String describing the socket's destination address and port.
  *
  * @return Socket description.
  */
 public String socketName() {
   return _sock.getInetAddress().toString() + ":" + _sock.getPort();
 }