public void close() {
    if (!real_socket.isClosed()) {
      synchronized (sinc_send_socket) {
        byte[] to_fin = new byte[Pacote.head_payload];
        OperacoesBinarias.inserirCabecalho(to_fin, 0, 0, false, false, false, true, 0, 0);
        DatagramPacket packet;
        if (is_server) {
          packet = new DatagramPacket(to_fin, Pacote.head_payload, client_adress, client_port);
        } else {
          packet = new DatagramPacket(to_fin, Pacote.head_payload, server_adress, server_port);
        }

        try {
          for (int i = 0; i < max_win && !real_socket.isClosed(); i++) {
            real_socket.send(packet);
          }
        } catch (IOException e) {
          System.out.println("Problema com socket interno");
          System.out.println("Fechando conexão...");
          close.set(true);
          e.printStackTrace();
        }
      }
      close.set(true);
      real_socket.close();
    }
  }
 /** Accept incoming events and processes them. */
 @Override
 public void run() {
   while (isActive()) {
     if (datagramSocket.isClosed()) {
       // OK we're done.
       return;
     }
     try {
       final byte[] buf = new byte[maxBufferSize];
       final DatagramPacket packet = new DatagramPacket(buf, buf.length);
       datagramSocket.receive(packet);
       final ByteArrayInputStream bais =
           new ByteArrayInputStream(packet.getData(), packet.getOffset(), packet.getLength());
       logEventInput.logEvents(logEventInput.wrapStream(bais), this);
     } catch (final OptionalDataException e) {
       if (datagramSocket.isClosed()) {
         // OK we're done.
         return;
       }
       logger.error("OptionalDataException eof=" + e.eof + " length=" + e.length, e);
     } catch (final EOFException e) {
       if (datagramSocket.isClosed()) {
         // OK we're done.
         return;
       }
       logger.info("EOF encountered");
     } catch (final IOException e) {
       if (datagramSocket.isClosed()) {
         // OK we're done.
         return;
       }
       logger.error("Exception encountered on accept. Ignoring. Stack Trace :", e);
     }
   }
 }
 /**
  * Closes the socket and stops the listener thread.
  *
  * @throws IOException
  */
 public void close() throws IOException {
   boolean interrupted = false;
   WorkerTask l = listener;
   if (l != null) {
     l.terminate();
     l.interrupt();
     if (socketTimeout > 0) {
       try {
         l.join();
       } catch (InterruptedException ex) {
         interrupted = true;
         logger.warn(ex);
       }
     }
     listener = null;
   }
   DatagramSocket closingSocket = socket;
   if ((closingSocket != null) && (!closingSocket.isClosed())) {
     closingSocket.close();
   }
   socket = null;
   if (interrupted) {
     Thread.currentThread().interrupt();
   }
 }
Beispiel #4
0
 // kill it with fire!
 public boolean close() {
   if (!socket.isClosed() || socket.isConnected()) {
     socket.close();
     return true;
   }
   return false;
 }
Beispiel #5
0
  public static void main(String[] args) {
    DatagramSocket socket = null;

    try {
      socket = new DatagramSocket(PORT);

      while (true) {
        DatagramPacket receivePacket = new DatagramPacket(new byte[256], 256);

        socket.receive(receivePacket);

        String date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
        byte[] sendData = date.getBytes(StandardCharsets.UTF_8);

        DatagramPacket sendPacket =
            new DatagramPacket(
                sendData,
                sendData.length,
                new InetSocketAddress(receivePacket.getAddress(), receivePacket.getPort()));
        socket.send(sendPacket);
      }
    } catch (SocketException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (socket != null && socket.isClosed() == false) {
        socket.close();
      }
    }
  }
  @Override
  public void run() {
    try {
      socket = new DatagramSocket(port);

      while (!isClosed) {
        if (socket.isClosed()) return;

        byte[] buf = new byte[256];

        // receive request
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        socket.receive(packet);

        ByteArrayInputStream bis = new ByteArrayInputStream(buf, 0, packet.getLength());
        BufferedReader in = new BufferedReader(new InputStreamReader(bis));

        String msg;
        while ((msg = in.readLine()) != null) {
          logger.debug("Read from socket: " + msg);
          content.add(msg.trim());
        }
        in.close();
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Beispiel #7
0
 @Override
 public void close() throws ChannelException {
   if (!socket.isClosed()) {
     socket.close();
     emitChannelClosed();
   }
 }
Beispiel #8
0
  public void run() {
    printWelcome();
    while (!welcomingSocket.isClosed()) {
      while (!canCreateNewWorker()) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          continue;
        }
      }

      try {
        DatagramPacket pkt = new DatagramPacket(new byte[EXPECTED_REQ_SIZE], EXPECTED_REQ_SIZE);
        welcomingSocket.receive(pkt); // Blocks!
        RequestPacket reqPkt = new RequestPacket(pkt);

        if (reqPkt.isCorrupted()) {
          continue;
        }

        ConnectionHandler conn = new ConnectionHandler(strategy, reqPkt, plp, pep, rngSeed, maxN);
        Thread connectionHandler = new Thread(conn);
        connectionHandler.start();
        workers.add(new Worker(connectionHandler, conn, System.currentTimeMillis()));
      } catch (IOException e) {
        continue;
      }
    }
  }
Beispiel #9
0
    public void run() {
      while (_datagramSocket != null && _datagramSocket == _socket && !_datagramSocket.isClosed()) {
        try {
          DatagramPacket packet = new DatagramPacket(new byte[MAX_PACKET_SIZE], MAX_PACKET_SIZE);
          _datagramSocket.receive(packet);
          DnsMessage answer = new DnsMessage();
          answer.decode(ByteBuffer.wrap(packet.getData()));
          MsgContainer msgContainer;

          synchronized (_queries) {
            msgContainer = _queries.get(answer.getHeaderSection().getId());
          }

          if (msgContainer != null) {
            synchronized (msgContainer.getQuery()) {
              msgContainer.setAnswer(answer);
              msgContainer.getQuery().notify();
            }
          } else LOG.warn("Drop DNS Answser {}, as can not found a query with same ID", answer);
        } catch (IOException e) {
          close();
        }
      }
      close();
      LOG.debug("DNS acceptor done");
    }
Beispiel #10
0
  // start up the server
  public void start() {
    DatagramSocket socket = null;
    try {
      // create a datagram socket, bind to port port. See
      // http://docs.oracle.com/javase/tutorial/networking/datagrams/ for
      // details.

      socket = new DatagramSocket(port);

      // receive packets in an infinite loop
      while (true) {
        // create an empty UDP packet
        byte[] buf = new byte[Server.MAX_PACKET_SIZE];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        // call receive (this will poulate the packet with the received
        // data, and the other endpoint's info)
        socket.receive(packet);
        // start up a worker thread to process the packet (and pass it
        // the socket, too, in case the
        // worker thread wants to respond)
        WorkerThread t = new WorkerThread(packet, socket);
        t.start();
      }
    } catch (IOException e) {
      // we jump out here if there's an error, or if the worker thread (or
      // someone else) closed the socket
      e.printStackTrace();
    } finally {
      if (socket != null && !socket.isClosed()) socket.close();
    }
  }
 public void run() {
   System.err.println("Sender start");
   while (!socket.isClosed()) {
     try {
       DatagramPacket packet = queue.take();
       if (Math.random() < 0.95) socket.send(packet);
     } catch (IOException ex) {
       System.out.println("Package was dropped because of IO exception");
       ex.printStackTrace();
       if (socket.isClosed()) break;
     } catch (InterruptedException ex) {
       continue;
     }
   }
   System.err.println("Sender stop");
   /* No cleanup here, either */
 }
 /** Close the server. */
 @Override
 public void close() {
   if (socket != null) {
     if (!socket.isClosed()) {
       socket.close();
       socket = null;
       LOGGER.info("Server is stopped");
     }
   }
 }
Beispiel #13
0
  public synchronized DatagramSocket getDatagramSocket() throws SocketException {
    if (_socket == null || _socket.isClosed()) {
      _socket = new DatagramSocket(getPort(), getHostAddr());
      _socket.setSoTimeout(_timeout); // FIXME

      LOG.debug(
          "Create the new datagram socket {} for DNS connector", _socket.getLocalSocketAddress());
      _acceptor = new Acceptor();
      new Thread(_acceptor, "DNS acceptor").start();
    }
    return _socket;
  }
 public void closeConnection() {
   try {
     if (pingAliveSocket != null) {
       if (!pingAliveSocket.isClosed()) {
         pingAliveSocket.close();
       }
     }
     if (clientSocket != null) {
       if (!clientSocket.isClosed()) {
         outData = "CONN_CLOSE".getBytes("UTF-8");
         outPacket = new DatagramPacket(outData, outData.length, srvAddr, serverPort);
         clientSocket.send(outPacket);
         clientSocket.close();
       }
     }
   } catch (Exception e) {
     if (DEBUG) {
       e.printStackTrace();
       Log.d(TAG, "Closure of connection failed! // SERVER MIGHT BE ALREADY UNREACHABLE!");
     }
   }
 }
 /**
  * A synchronized function for closing the UPD socket. It prevents the situation in which both the
  * listener thread and the GUI thread close the socket at the same time.
  */
 private synchronized void closeSocket() {
   if (ds != null) {
     if (ds.isConnected()) {
       ds.disconnect();
     }
     if (!ds.isClosed()) {
       ds.close();
     }
     ds = null;
     if (Debug.SHOW_PROXY_VEHICLE_DEBUG_MSG) {
       System.err.println("The UDP socket is closed.");
     }
   }
 }
  protected boolean func_72604_a(DatagramSocket p_72604_1_, boolean p_72604_2_) {
    this.func_72607_a("closeSocket: " + p_72604_1_);
    if (null == p_72604_1_) {
      return false;
    } else {
      boolean var3 = false;
      if (!p_72604_1_.isClosed()) {
        p_72604_1_.close();
        var3 = true;
      }

      if (p_72604_2_) {
        this.field_72616_e.remove(p_72604_1_);
      }

      return var3;
    }
  }
  /** Closes the specified DatagramSocket */
  protected boolean closeSocket(DatagramSocket par1DatagramSocket, boolean par2) {
    logDebug("closeSocket: " + par1DatagramSocket);

    if (null == par1DatagramSocket) {
      return false;
    } else {
      boolean var3 = false;

      if (!par1DatagramSocket.isClosed()) {
        par1DatagramSocket.close();
        var3 = true;
      }

      if (par2) {
        socketList.remove(par1DatagramSocket);
      }

      return var3;
    }
  }
Beispiel #18
0
  @Override
  public void run() {
    // TODO Para leer mensajes enviados por el servidor

    while (!udpSocket.isClosed()) {
      DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
      try {

        udpSocket.receive(receivePacket);

        byte[] c;
        c = Arrays.copyOf(receivePacket.getData(), receivePacket.getLength());
        String id = receivePacket.getAddress().toString() + ":" + receivePacket.getPort();

        this.onMessageReceived(c, id.replace("/", ""));

      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Beispiel #19
0
  /** Sends the message to a recipient */
  private void sendMessage(
      DatagramSocket socket,
      String label,
      InetSocketAddress to,
      NameServicesChannelMessage message) {
    if (isSameSocketAddress(socket, to))
      _logger.info("{} sending message. to=self, message={}", label, message);
    else _logger.info("{} sending message. to={}, message={}", label, to, message);

    if (socket == null) {
      _logger.info("{} is not available yet; ignoring send request.", label);
      return;
    }

    // convert into bytes
    String json = Serialisation.serialise(message);
    byte[] bytes = json.getBytes(UTF8Charset.instance());

    DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
    packet.setSocketAddress(to);

    try {
      socket.send(packet);

      if (to.getAddress().isMulticastAddress()) {
        s_multicastOutData.addAndGet(bytes.length);
        s_multicastOutOps.incrementAndGet();
      } else {
        s_unicastOutData.addAndGet(bytes.length);
        s_unicastOutOps.incrementAndGet();
      }

    } catch (IOException exc) {
      if (!_enabled) return;

      if (socket.isClosed())
        _logger.info(s_sendSocketLabel + " send() ignored as socket is being recycled.");
      else _logger.warn(s_sendSocketLabel + " send() failed. ", exc);
    }
  } // (method)
  @Override
  void send(byte[] data) {

    byte[] protocolAndData = new byte[data.length + 3];

    System.arraycopy(data, 0, protocolAndData, 2, data.length);

    protocolAndData[0] = (byte) 0;
    protocolAndData[1] = (byte) 0;
    protocolAndData[protocolAndData.length - 1] = (byte) 255;

    if (log) {
      System.out.println(
          this.id
              + ", universe "
              + universe
              + " at IP "
              + this.ipStr
              + ":"
              + bytesToHex(protocolAndData, protocolAndData.length));
    }

    synchronized (this) {
      if (socket == null || socket.isClosed()) {
        try {
          socket = new DatagramSocket(port);
          DatagramPacket packet =
              new DatagramPacket(protocolAndData, protocolAndData.length, ip, port);
          socket.send(packet);
        } catch (SocketException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
 public void run() {
   DatagramSocket socketCopy = socket;
   if (socketCopy != null) {
     try {
       socketCopy.setSoTimeout(getSocketTimeout());
       if (receiveBufferSize > 0) {
         socketCopy.setReceiveBufferSize(Math.max(receiveBufferSize, maxInboundMessageSize));
       }
       if (logger.isDebugEnabled()) {
         logger.debug(
             "UDP receive buffer size for socket "
                 + getAddress()
                 + " is set to: "
                 + socketCopy.getReceiveBufferSize());
       }
     } catch (SocketException ex) {
       logger.error(ex);
       setSocketTimeout(0);
     }
   }
   while (!stop) {
     DatagramPacket packet =
         new DatagramPacket(buf, buf.length, udpAddress.getInetAddress(), udpAddress.getPort());
     try {
       socketCopy = socket;
       try {
         if (socketCopy == null) {
           stop = true;
           continue;
         }
         socketCopy.receive(packet);
       } catch (InterruptedIOException iiox) {
         if (iiox.bytesTransferred <= 0) {
           continue;
         }
       }
       if (logger.isDebugEnabled()) {
         logger.debug(
             "Received message from "
                 + packet.getAddress()
                 + "/"
                 + packet.getPort()
                 + " with length "
                 + packet.getLength()
                 + ": "
                 + new OctetString(packet.getData(), 0, packet.getLength()).toHexString());
       }
       ByteBuffer bis;
       // If messages are processed asynchronously (i.e. multi-threaded)
       // then we have to copy the buffer's content here!
       if (isAsyncMsgProcessingSupported()) {
         byte[] bytes = new byte[packet.getLength()];
         System.arraycopy(packet.getData(), 0, bytes, 0, bytes.length);
         bis = ByteBuffer.wrap(bytes);
       } else {
         bis = ByteBuffer.wrap(packet.getData());
       }
       TransportStateReference stateReference =
           new TransportStateReference(
               DefaultUdpTransportMapping.this,
               udpAddress,
               null,
               SecurityLevel.undefined,
               SecurityLevel.undefined,
               false,
               socketCopy);
       fireProcessMessage(
           new UdpAddress(packet.getAddress(), packet.getPort()), bis, stateReference);
     } catch (SocketTimeoutException stex) {
       // ignore
     } catch (PortUnreachableException purex) {
       synchronized (DefaultUdpTransportMapping.this) {
         listener = null;
       }
       logger.error(purex);
       if (logger.isDebugEnabled()) {
         purex.printStackTrace();
       }
       if (SNMP4JSettings.isFowardRuntimeExceptions()) {
         throw new RuntimeException(purex);
       }
       break;
     } catch (SocketException soex) {
       if (!stop) {
         logger.error(
             "Socket for transport mapping " + toString() + " error: " + soex.getMessage(),
             soex);
       }
       if (SNMP4JSettings.isFowardRuntimeExceptions()) {
         stop = true;
         throw new RuntimeException(soex);
       }
     } catch (IOException iox) {
       logger.warn(iox);
       if (logger.isDebugEnabled()) {
         iox.printStackTrace();
       }
       if (SNMP4JSettings.isFowardRuntimeExceptions()) {
         throw new RuntimeException(iox);
       }
     }
   }
   synchronized (DefaultUdpTransportMapping.this) {
     listener = null;
     stop = true;
     DatagramSocket closingSocket = socket;
     if ((closingSocket != null) && (!closingSocket.isClosed())) {
       closingSocket.close();
     }
   }
   if (logger.isDebugEnabled()) {
     logger.debug("Worker task stopped:" + getClass().getName());
   }
 }
  // start up the server
  public void start() {
    DatagramSocket socket = null;
    try {

      InetSocketAddress serverSocketAddress = new InetSocketAddress(serverAddress, serverPort);

      // create a datagram socket, let the OS bind to an ephemeral UDP
      // port. See
      // http://docs.oracle.com/javase/tutorial/networking/datagrams/ for
      // details.
      socket = new DatagramSocket();

      // send "REGISTER" to the server
      //
      // create an UDP packet that we'll send to the server
      String command = "REGISTER";
      DatagramPacket txPacket =
          new DatagramPacket(command.getBytes(), command.length(), serverSocketAddress);
      // send the packet through the socket to the server
      socket.send(txPacket);

      // receive the server's response
      //
      // create an empty UDP packet
      byte[] buf = new byte[Server.MAX_PACKET_SIZE];
      DatagramPacket rxPacket = new DatagramPacket(buf, buf.length);
      // call receive (this will poulate the packet with the received
      // data, and the other endpoint's info)
      socket.receive(rxPacket);
      // print the payload
      String payload = new String(rxPacket.getData(), 0, rxPacket.getLength());
      System.out.println(payload);

      // send "SEND Hello everybody!" to the server
      //
      command =
          "SEND Hello everybody! The time is "
              + new SimpleDateFormat("HH:mm:ss").format(new Date());
      txPacket = new DatagramPacket(command.getBytes(), command.length(), serverSocketAddress);
      socket.send(txPacket);

      // receive the server's response
      //
      socket.receive(rxPacket);
      // print the payload
      payload = new String(rxPacket.getData(), 0, rxPacket.getLength());
      System.out.println(payload);

      // and then keep on receiving packets in an infinite loop
      while (true) {
        socket.receive(rxPacket);
        payload = new String(rxPacket.getData(), 0, rxPacket.getLength());
        System.out.println(payload);
      }
    } catch (IOException e) {
      // we jump out here if there's an error
      e.printStackTrace();
    } finally {
      // close the socket
      if (socket != null && !socket.isClosed()) socket.close();
    }
  }
  public List<MsgEvent> discover() {
    List<MsgEvent> discoveryList = null;
    // Find the server using UDP broadcast
    try {
      discoveryList = new ArrayList<MsgEvent>();
      // Open a random port to send the package
      c = new DatagramSocket();
      c.setBroadcast(true);

      byte[] sendData = "DISCOVER_FUIFSERVER_REQUEST".getBytes();

      // Try the 255.255.255.255 first
      try {
        DatagramPacket sendPacket =
            new DatagramPacket(
                sendData, sendData.length, InetAddress.getByName("255.255.255.255"), 32005);
        c.send(sendPacket);
        // System.out.println(getClass().getName() + ">>> Request packet sent to: 255.255.255.255
        // (DEFAULT)");
      } catch (Exception e) {
      }

      // Broadcast the message over all the network interfaces
      Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
      while (interfaces.hasMoreElements()) {
        NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();

        if (networkInterface.isLoopback() || !networkInterface.isUp()) {
          continue; // Don't want to broadcast to the loopback interface
        }

        for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
          InetAddress broadcast = interfaceAddress.getBroadcast();
          if (broadcast == null) {
            continue;
          }

          // Send the broadcast package!
          try {
            DatagramPacket sendPacket =
                new DatagramPacket(sendData, sendData.length, broadcast, 32005);
            c.send(sendPacket);
          } catch (Exception e) {
          }

          // System.out.println(getClass().getName() + ">>> Request packet sent to: " +
          // broadcast.getHostAddress() + "; Interface: " + networkInterface.getDisplayName());
        }
      }

      // System.out.println(getClass().getName() + ">>> Done looping over all network interfaces.
      // Now waiting for a reply!");

      // Wait for a response
      while (!c.isClosed()) {
        try {
          byte[] recvBuf = new byte[15000];
          DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
          c.receive(receivePacket);

          // We have a response
          // System.out.println(getClass().getName() + ">>> Broadcast response from server: " +
          // receivePacket.getAddress().getHostAddress());

          // Check if the message is correct
          // System.out.println(new String(receivePacket.getData()));

          String json = new String(receivePacket.getData()).trim();
          // String response = "region=region0,agent=agent0,recaddr=" +
          // packet.getAddress().getHostAddress();
          try {
            MsgEvent me = gson.fromJson(json, MsgEvent.class);
            if (me != null) {
              if (!me.getParam("clientip").equals(receivePacket.getAddress().getHostAddress())) {
                // System.out.println("SAME HOST");
                // System.out.println(me.getParamsString() +
                // receivePacket.getAddress().getHostAddress());
                me.setParam("serverip", receivePacket.getAddress().getHostAddress());
                discoveryList.add(me);
              }
            }
          } catch (Exception ex) {
            System.out.println("in loop 0" + ex.toString());
          }
        } catch (SocketException ex) {
          // eat message.. this should happen
        } catch (Exception ex) {
          System.out.println("in loop 1" + ex.toString());
        }
      }
      // Close the port!
      // c.close();
      // System.out.println("CODY : Dicsicer Client Worker Engned!");
    } catch (Exception ex) {
      System.out.println("while not closed: " + ex.toString());
    }
    return discoveryList;
  }
Beispiel #24
0
 private void close() {
   if (_datagramSocket != null && !_datagramSocket.isClosed()) _datagramSocket.close();
   _datagramSocket = null;
 }