public void run() {
    System.out.println("ExeUDPServer开始监听..." + UDP_PORT);
    DatagramSocket ds = null;
    try {
      ds = new DatagramSocket(UDP_PORT);
    } catch (BindException e) {
      System.out.println("UDP端口使用中...请重关闭程序启服务器");
    } catch (SocketException e) {
      e.printStackTrace();
    }

    while (ds != null) {
      DatagramPacket dp = new DatagramPacket(buf, buf.length);
      try {
        ds.receive(dp);
        // 得到把该数据包发来的端口和Ip
        int rport = dp.getPort();
        InetAddress addr = dp.getAddress();
        String recvStr = new String(dp.getData(), 0, dp.getLength());
        System.out.println("Server receive:" + recvStr + " from " + addr + "  " + rport);

        // 给客户端回应
        String sendStr = "echo of " + recvStr;
        byte[] sendBuf;
        sendBuf = sendStr.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length, addr, rport);
        ds.send(sendPacket);

      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
 public static void main(String args[]) {
   DatagramSocket aSocket = null;
   try {
     aSocket = new DatagramSocket();
     String stringMsg = "0";
     String prevReply = "0";
     InetAddress aHost =
         InetAddress.getByName("localhost"); // recieve a message from the same computer
     int serverPort = 6789; // agreed port
     while (true) {
       stringMsg = "" + (Integer.parseInt(stringMsg) + 1);
       byte[] message = stringMsg.getBytes();
       DatagramPacket request = new DatagramPacket(message, message.length, aHost, serverPort);
       System.out.printf("Producer: Sending: %s\n", stringMsg);
       aSocket.send(request); // send a message
       byte[] buffer = new byte[1000];
       DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
       aSocket.receive(reply); // wait for a reply
       try {
         Thread.sleep(2000); // have a small waiting period
       } catch (InterruptedException e) {
       }
     }
   } catch (SocketException e) {
     System.out.println("Socket: " + e.getMessage());
   } catch (IOException e) {
     System.out.println("IO: " + e.getMessage());
   } finally {
     if (aSocket != null) aSocket.close();
   }
 }
  private Core() {
    boolean f = false;
    try {
      for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
        NetworkInterface intf = (NetworkInterface) en.nextElement();
        for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
          InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
          if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
            String ipAddress = inetAddress.getHostAddress().toString();
            this.ip = inetAddress;
            f = true;
            break;
          }
        }
        if (f) break;
      }
    } catch (SocketException ex) {
      ex.printStackTrace();
      System.exit(1);
    }
    this.teams = new HashMap<String, Team>();
    this.judges = new HashMap<String, Judge>();
    this.problems = new HashMap<String, ProblemInfo>();
    this.scheduler = new Scheduler();
    this.timer = new ContestTimer(300 * 60);

    try {
      readConfigure();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      System.exit(1);
    }
    this.scoreBoardHttpServer = new ScoreBoardHttpServer(this.scoreBoardPort);
  }
 public void setSoTimeout(int timeout) {
   try {
     _socket.setSoTimeout(timeout);
   } catch (SocketException e) {
     e.printStackTrace();
   }
 }
Beispiel #5
0
 Server() {
   try {
     receiveSocket = new DatagramSocket(thisPort);
   } catch (SocketException se) {
     se.printStackTrace();
     System.exit(1);
   }
   running = true;
 }
Beispiel #6
0
 public static void main(String[] args) throws Exception {
   startServer();
   try {
     doClientSide();
   } catch (SocketException e) {
     if (!e.getMessage().equalsIgnoreCase("Socket closed")) {
       throw new Exception("Received a wrong exception message: " + e.getMessage());
     }
     System.out.println("PASSED: received the right exception message: " + e.getMessage());
   }
   if (serverException != null) {
     throw serverException;
   }
 }
  /**
   * Initializes and binds a socket that on a random port number. The method would try to bind on a
   * random port and retry 5 times until a free port is found.
   *
   * @return the socket that we have initialized on a randomport number.
   */
  private DatagramSocket initRandomPortSocket() {
    DatagramSocket resultSocket = null;
    String bindRetriesStr =
        NetaddrActivator.getConfigurationService().getString(BIND_RETRIES_PROPERTY_NAME);

    int bindRetries = 5;

    if (bindRetriesStr != null) {
      try {
        bindRetries = Integer.parseInt(bindRetriesStr);
      } catch (NumberFormatException ex) {
        logger.error(
            bindRetriesStr
                + " does not appear to be an integer. "
                + "Defaulting port bind retries to "
                + bindRetries,
            ex);
      }
    }

    int currentlyTriedPort = NetworkUtils.getRandomPortNumber();

    // we'll first try to bind to a random port. if this fails we'll try
    // again (bindRetries times in all) until we find a free local port.
    for (int i = 0; i < bindRetries; i++) {
      try {
        resultSocket = new DatagramSocket(currentlyTriedPort);
        // we succeeded - break so that we don't try to bind again
        break;
      } catch (SocketException exc) {
        if (exc.getMessage().indexOf("Address already in use") == -1) {
          logger.fatal(
              "An exception occurred while trying to create" + "a local host discovery socket.",
              exc);
          resultSocket = null;
          return null;
        }
        // port seems to be taken. try another one.
        logger.debug("Port " + currentlyTriedPort + " seems in use.");
        currentlyTriedPort = NetworkUtils.getRandomPortNumber();
        logger.debug("Retrying bind on port " + currentlyTriedPort);
      }
    }

    return resultSocket;
  }
 /**
  * Main method keeps waiting for request and do math operation accordingly
  *
  * @param args
  */
 public static void main(String args[]) {
   DatagramSocket aSocket = null;
   try {
     aSocket = new DatagramSocket(6789);
     byte[] buffer = new byte[1000];
     while (true) {
       DatagramPacket request = new DatagramPacket(buffer, buffer.length);
       aSocket.receive(request);
       // receive byte array of equation and put it in string
       String equation = new String(request.getData());
       String answer = "";
       String[] split = equation.split(" ");
       // parse to integer and calculate
       String op = split[1];
       double var1 = Double.parseDouble(split[0]);
       double var2 = Double.parseDouble(split[2]);
       if (op.equals("+")) {
         answer = Double.toString(var1 + var2);
       } else if (op.equals("-")) {
         answer = Double.toString(var1 - var2);
       } else if (op.toLowerCase().equals("X") || op.toLowerCase().equals("x")) {
         answer = Double.toString(var1 * var2);
       } else if (op.equals("/")) {
         answer = Double.toString(var1 / var2);
       }
       // send answer back
       DatagramPacket reply =
           new DatagramPacket(
               answer.getBytes(),
               (answer.getBytes()).length,
               request.getAddress(),
               request.getPort());
       aSocket.send(reply);
     }
   } catch (SocketException e) {
     System.out.println("Socket: " + e.getMessage());
   } catch (IOException e) {
     System.out.println("IO: " + e.getMessage());
   } finally {
     if (aSocket != null) {
       aSocket.close();
     }
   }
 }
Beispiel #9
0
  public void run() {
    while (Thread.currentThread() == thread) {
      try {
        Socket socket = server.accept();
        Client client = new Client(parent, socket);

        if (clientValidationMethod != null) {
          try {
            clientValidationMethod.invoke(parent, new Object[] {this, client});
          } catch (Exception e) {
            // System.err.println("Disabling serverEvent() for port " + port);
            e.printStackTrace();
          }
        }

        if (client.active()) {
          synchronized (clients) {
            addClient(client);
            if (serverEventMethod != null) {
              try {
                serverEventMethod.invoke(parent, new Object[] {this, client});
              } catch (Exception e) {
                // System.err.println("Disabling serverEvent() for port " + port);
                e.printStackTrace();
              }
            }
          }
        }
      } catch (SocketException e) {
        // thrown when server.close() is called and server is waiting on accept
        System.err.println("Server SocketException: " + e.getMessage());
        thread = null;
      } catch (IOException e) {
        // errorMessage("run", e);
        e.printStackTrace();
        thread = null;
      }
      try {
        Thread.sleep(8);
      } catch (InterruptedException ex) {
      }
    }
  }
Beispiel #10
0
  // sends a response to the Client based upon the contents of the receive packet
  private void reply(DatagramPacket receivedPacket) {
    // verify the packet
    byte serverMsg[] = {};
    try {
      Request recReq = new Request(receivedPacket.getData(), receivedPacket.getLength());
      if (!recReq.isValid()) {
        throw new IllegalStateException();
      }
      switch (recReq.getFormat()) {
        case RRQ:
          serverMsg = new byte[] {0, 3, 0, 1};
          break;
        case WRQ:
          serverMsg = new byte[] {0, 4, 0, 0};
          break;
        default:
          throw new IllegalStateException();
      }
    } catch (IllegalStateException e) {
      e.printStackTrace();
      System.exit(1);
    }

    DatagramPacket sendPacket =
        new DatagramPacket(
            serverMsg, serverMsg.length, receivedPacket.getAddress(), receivedPacket.getPort());

    readSendPacket(sendPacket);

    try {
      // Send the datagram packet to the client via the send socket.
      DatagramSocket sendSocket = new DatagramSocket();
      sendSocket.send(sendPacket);
      sendSocket.close();
    } catch (SocketException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
      System.exit(1);
    }

    System.out.println("Server: packet sent.\n");
  }
Beispiel #11
0
 @Override
 public void run() {
   while (true) {
     try {
       String wsName = EncodeDecode.decodeString(receive());
       Integer paramCnt = Integer.parseInt(EncodeDecode.decodeString(receive()));
       String params[] = new String[paramCnt];
       for (int i = 0; i < paramCnt; i++) {
         params[i] = EncodeDecode.decodeString(receive());
       }
       String result = internal_call(wsName, params);
       send(EncodeDecode.encode(result));
     } catch (NumberFormatException e) {
       logger.info("number format error");
       return;
     } catch (SocketException e) {
       logger.info("socket " + e.getMessage());
       return;
     }
   }
 }
 public String getLocalIpAddress() {
   try {
     for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
         en.hasMoreElements(); ) {
       NetworkInterface intf = en.nextElement();
       for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
           enumIpAddr.hasMoreElements(); ) {
         InetAddress inetAddress = enumIpAddr.nextElement();
         // if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() &&
         // inetAddress.isSiteLocalAddress() ) {
         if (!inetAddress.isLoopbackAddress()
             && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
           String ipAddr = inetAddress.getHostAddress();
           return ipAddr;
         }
       }
     }
   } catch (SocketException ex) {
     Log.d(TAG, ex.toString());
   }
   return null;
 }
Beispiel #13
0
 public static void showNIC() {
   // http://www.informatik-blog.net/2009/01/28/informationen-der-netzwerkkarten-auslesen/
   try {
     Enumeration<NetworkInterface> interfaceNIC = NetworkInterface.getNetworkInterfaces();
     // Alle Schnittstellen durchlaufen
     while (interfaceNIC.hasMoreElements()) {
       // Elemente abfragen und ausgeben
       NetworkInterface n = interfaceNIC.nextElement();
       System.out.println(
           String.format("Netzwerk-Interface: %s (%s)", n.getName(), n.getDisplayName()));
       // Adressen abrufen
       Enumeration<InetAddress> addresses = n.getInetAddresses();
       // Adressen durchlaufen
       while (addresses.hasMoreElements()) {
         InetAddress address = addresses.nextElement();
         System.out.println(String.format("- %s", address.getHostAddress()));
       }
     }
     System.out.println();
   } catch (SocketException e) {
     e.printStackTrace();
   }
 }
  public boolean makeconnection() {

    if (serversoc == null || serversoc.isClosed()) {
      try {
        serversoc = new ServerSocket(portnum);
        serversoc.setSoTimeout(0);
      } catch (IOException ex) {
        logger.warning(ex.getMessage());
      }
    }

    try {
      System.out.println("server waiting");
      mysocket = serversoc.accept();

      in = mysocket.getInputStream();
      out = mysocket.getOutputStream();

      oos = new ObjectOutputStream(out);
      ois = new ObjectInputStream(in);

      System.out.println("connection established");

      waitforreceivingdata();
      return true;
    } catch (SocketException ex) {
      logger.warning(ex.getMessage());
      return false;
    } catch (IOException ex) {
      logger.warning(ex.getMessage());
      return false;
    } catch (Exception ex) {
      logger.warning(ex.getMessage());
      return false;
    }
  }
 /**
  * Discover WS device on the local network
  *
  * @return list of unique devices access strings which might be URLs in most cases
  */
 public static Collection<String> discoverWsDevices() {
   final Collection<String> addresses = new ConcurrentSkipListSet<>();
   final CountDownLatch serverStarted = new CountDownLatch(1);
   final CountDownLatch serverFinished = new CountDownLatch(1);
   final Collection<InetAddress> addressList = new ArrayList<>();
   try {
     final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
     if (interfaces != null) {
       while (interfaces.hasMoreElements()) {
         NetworkInterface anInterface = interfaces.nextElement();
         if (!anInterface.isLoopback()) {
           final List<InterfaceAddress> interfaceAddresses = anInterface.getInterfaceAddresses();
           for (InterfaceAddress address : interfaceAddresses) {
             addressList.add(address.getAddress());
           }
         }
       }
     }
   } catch (SocketException e) {
     e.printStackTrace();
   }
   ExecutorService executorService = Executors.newCachedThreadPool();
   for (final InetAddress address : addressList) {
     Runnable runnable =
         new Runnable() {
           public void run() {
             try {
               final String uuid = UUID.randomUUID().toString();
               final String probe =
                   WS_DISCOVERY_PROBE_MESSAGE.replaceAll(
                       "<wsa:MessageID>urn:uuid:.*</wsa:MessageID>",
                       "<wsa:MessageID>urn:uuid:" + uuid + "</wsa:MessageID>");
               final int port = random.nextInt(20000) + 40000;
               @SuppressWarnings("SocketOpenedButNotSafelyClosed")
               final DatagramSocket server = new DatagramSocket(port, address);
               new Thread() {
                 public void run() {
                   try {
                     final DatagramPacket packet = new DatagramPacket(new byte[4096], 4096);
                     server.setSoTimeout(WS_DISCOVERY_TIMEOUT);
                     long timerStarted = System.currentTimeMillis();
                     while (System.currentTimeMillis() - timerStarted < (WS_DISCOVERY_TIMEOUT)) {
                       serverStarted.countDown();
                       server.receive(packet);
                       final Collection<String> collection =
                           parseSoapResponseForUrls(
                               Arrays.copyOf(packet.getData(), packet.getLength()));
                       for (String key : collection) {
                         addresses.add(key);
                       }
                     }
                   } catch (SocketTimeoutException ignored) {
                   } catch (Exception e) {
                     e.printStackTrace();
                   } finally {
                     serverFinished.countDown();
                     server.close();
                   }
                 }
               }.start();
               try {
                 serverStarted.await(1000, TimeUnit.MILLISECONDS);
               } catch (InterruptedException e) {
                 e.printStackTrace();
               }
               if (address instanceof Inet4Address) {
                 server.send(
                     new DatagramPacket(
                         probe.getBytes(),
                         probe.length(),
                         InetAddress.getByName(WS_DISCOVERY_ADDRESS_IPv4),
                         WS_DISCOVERY_PORT));
               } else {
                 server.send(
                     new DatagramPacket(
                         probe.getBytes(),
                         probe.length(),
                         InetAddress.getByName(WS_DISCOVERY_ADDRESS_IPv6),
                         WS_DISCOVERY_PORT));
               }
             } catch (Exception e) {
               e.printStackTrace();
             }
             try {
               serverFinished.await((WS_DISCOVERY_TIMEOUT), TimeUnit.MILLISECONDS);
             } catch (InterruptedException e) {
               e.printStackTrace();
             }
           }
         };
     executorService.submit(runnable);
   }
   try {
     executorService.shutdown();
     executorService.awaitTermination(WS_DISCOVERY_TIMEOUT + 2000, TimeUnit.MILLISECONDS);
   } catch (InterruptedException ignored) {
   }
   return addresses;
 }
  /**
   * Create a multicast socket and join the multicast group. This method creates a multicast socket
   * that is used to broadcast The <CODE>DiscoveryResponder</CODE> will then join the multicast
   * group and send a join message. This method has no effect if the <CODE>DiscoveryResponder</CODE>
   * is <CODE>ONLINE</CODE> or <CODE>STOPPING</CODE> or <CODE>STARTING</CODE>.
   *
   * @exception IOException The creation of the Multicast socket failed.
   */
  public void start() throws IOException {
    if (state == OFFLINE) {
      changeState(STARTING);
      if (cmf == null) {
        if (logger.finerOn()) {
          logger.finer("start ", "Can't start discoveryResponder: JDMK MBeanServer is not set");
        }
        return;
      }

      // ----------------
      // Create a new obj to receive multicast msg ;
      // ----------------
      try {
        if (logger.finerOn()) {
          logger.finer("start ", "Create a new responder");
        }
        responder =
            new ActualResponder(multicastGroup, multicastPort, getTimeToLive(), cmf, spy, this);

        if (local != null) {
          responder.setLocalHost(local);
        }

        // NPCTE fix for bugId 4499338, esc 0, 04 Sept 2001
        if (usrInet != null) {
          responder.setInterface(usrInet);

          if (logger.finerOn()) {
            logger.finer("start ", "set interface to " + usrInet);
          }
        }
        // end of NPCTE fix for bugId 4499338

        if (noEvent != null) responder.noEvent();

        if (logger.finerOn()) {
          logger.finer("start ", "call responder connect");
        }
        responder.connectToGroup();

        // ----------------
        // Create a new thread to receive multicast msg ;
        // ----------------
        // responderThread = cmf.getThreadAllocatorSrvIf().obtainThread(responderObjectName,
        // responder);
        responderThread = new Thread(responder);
        responderThread.setName("Multicast responder");

        // ----------------
        // Start thread
        // ----------------
        responderThread.start();

        // ----------------
        // Update state
        // ----------------
        // changeState(ONLINE) ;
      } catch (SocketException e) {
        if (logger.finestOn()) {
          logger.finest("start", e);
        }
        throw new IOException(e.getMessage());

      } catch (IOException e) {
        // ------------------------
        // Keep exception for us
        // ------------------------
        if (logger.finestOn()) {
          logger.finest("start ", e);
        }
        throw e;
      } catch (NullPointerException e) {
        // ------------------------
        // the set group did not worked
        // ------------------------
        if (logger.finestOn()) {
          logger.finest("start ", e);
        }
        throw new IOException(e.getMessage());
      }
    } else {
      if (logger.finerOn()) {
        logger.finer("start ", "Responder is not OFFLINE");
      }
    }
  }