Beispiel #1
1
  public void run() {
    if (ServerSocket == null) return;
    while (true) {
      try {
        InetAddress address;
        int port;
        DatagramPacket packet;
        byte[] data = new byte[1460];
        packet = new DatagramPacket(data, data.length);
        ServerSocket.receive(packet);
        //
        //
        address = packet.getAddress();
        port = packet.getPort();
        System.out.println("get the Client port is: " + port);
        System.out.println("get the data length is: " + data.length);

        FileWriter fw = new FileWriter("Fortunes.txt");
        PrintWriter out = new PrintWriter(fw);
        for (int i = 0; i < data.length; i++) {
          out.print(data[i] + "  ");
        }
        out.close();
        System.out.println("Data has been writen to destination!");

        packet = new DatagramPacket(data, data.length, address, port);
        ServerSocket.send(packet);
        System.out.println("Respond has been made!");
      } catch (Exception e) {
        System.err.println("Exception: " + e);
        e.printStackTrace();
      }
    }
  }
Beispiel #2
0
  @Override
  public void run() {

    DatagramSocket socket;
    int clientListnport = Constants.UDPPort;

    try {
      // Keep a socket open to listen to all the UDP trafic that is
      // destined for this port
      socket = new DatagramSocket(clientListnport, (Inet4Address) InetAddress.getByName("0.0.0.0"));
      socket.setBroadcast(true);
      socket.setSoTimeout(10000);

      while (WifiReceiver.isWifi) {
        System.out.println(">>>Ready to receive broadcast packets!");

        // Receive a packet
        byte[] recvBuf = new byte[15000];
        DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
        try {
          socket.receive(packet);

          // Packet received
          System.out.println(
              ">>>Discovery packet received from: " + packet.getAddress().getHostAddress());
          // See if the packet holds the right command (message)
          String message = new String(packet.getData()).trim();
          if (message.equals(Constants.serverDiscoverString)) {
            byte[] sendData = Constants.clientReplyString.getBytes();
            // Send a response

            if (!WifiUtils.getipAddress()
                .equalsIgnoreCase(packet.getAddress().getHostAddress().toString())) {
              DatagramPacket sendPacket =
                  new DatagramPacket(
                      sendData, sendData.length, packet.getAddress(), packet.getPort());
              socket.send(sendPacket);

              System.out.println(">>>Sent packet to: " + sendPacket.getAddress().getHostAddress());
            }
          } else if (message.equals(Constants.serverFileSending)) {
            System.out.println("sending reply to recive handshake");
            byte[] sendData = Constants.clientFileReceive.getBytes();
            DatagramPacket sendPacket =
                new DatagramPacket(
                    sendData, sendData.length, packet.getAddress(), packet.getPort());
            socket.send(sendPacket);
            Log.d(loggerTag, "handshaking is done");
            FileReceiver.waitConnection();
          }
        } catch (SocketTimeoutException e) {
          // no need of doing anything
        }
      }
      System.out.println("CLientListener : Listener is stoped");
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
  @Override
  public void run() {
    while (true) {
      try {
        byte[] dataBuffer = new byte[25600]; // 25kB buffer
        DatagramPacket packet = new DatagramPacket(dataBuffer, dataBuffer.length);
        multiplexerSocket.receive(packet);
        // Check if packet is valid
        int type = dataBuffer[0] >>> 4;
        int version = dataBuffer[0] & 0x7;
        if (version == Packet.VERSION) {
          try {
            Packet utpPacket = packetFactory.getFromId(type);
            Stream inStream = new Stream(packet.getData(), packet.getOffset(), packet.getLength());
            utpPacket.read(inStream);
            UtpSocket socket = new UtpSocket(utpPacket.getConnectionId());
            socket = utpSockets.find(socket);
            if (socket != null) {
              // log("Received " + utpPacket.getClass().getSimpleName() + " for " +
              // (utpPacket.getConnectionId() & 0xFFFF));
              socket.updateLastInteraction();
              utpPacket.process(socket);
            } else {
              // log("Packet of " + packet.getLength() + " bytes (0x" +
              // Integer.toHexString(dataBuffer[0]) + ") was send to a connection which was not
              // established (" + packet.getAddress() + ":" + packet.getPort() + " | " +
              // utpPacket.getConnectionId() + ")");
            }
          } catch (IllegalArgumentException e) {
            log(
                "Invalid Packet of "
                    + packet.getLength()
                    + " bytes with type "
                    + type
                    + " ("
                    + packet.getAddress()
                    + ":"
                    + packet.getPort()
                    + ")",
                true);
          }
        } else {
          log(
              "Invalid Packet of "
                  + packet.getLength()
                  + " bytes with version "
                  + version
                  + " ("
                  + packet.getAddress()
                  + ":"
                  + packet.getPort()
                  + ")",
              true);
        }
      } catch (IOException e) {

      }
    }
  }
  @Scheduled(fixedDelay = Integer.MAX_VALUE)
  public void startListening() {

    if (disable) {
      return;
    }

    log.info("Starting UPNP Discovery Listener");

    try (DatagramSocket responseSocket = new DatagramSocket(upnpResponsePort);
        MulticastSocket upnpMulticastSocket = new MulticastSocket(UPNP_DISCOVERY_PORT); ) {
      InetSocketAddress socketAddress =
          new InetSocketAddress(UPNP_MULTICAST_ADDRESS, UPNP_DISCOVERY_PORT);
      Enumeration<NetworkInterface> ifs = NetworkInterface.getNetworkInterfaces();

      while (ifs.hasMoreElements()) {
        NetworkInterface xface = ifs.nextElement();
        Enumeration<InetAddress> addrs = xface.getInetAddresses();
        String name = xface.getName();
        int IPsPerNic = 0;

        while (addrs.hasMoreElements()) {
          InetAddress addr = addrs.nextElement();
          log.debug(name + " ... has addr " + addr);
          if (InetAddressUtils.isIPv4Address(addr.getHostAddress())) {
            IPsPerNic++;
          }
        }
        log.debug("Checking " + name + " to our interface set");
        if (IPsPerNic > 0) {
          upnpMulticastSocket.joinGroup(socketAddress, xface);
          log.debug("Adding " + name + " to our interface set");
        }
      }

      while (true) { // trigger shutdown here
        byte[] buf = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        upnpMulticastSocket.receive(packet);
        String packetString = new String(packet.getData());
        if (isSSDPDiscovery(packetString)) {
          log.debug(
              "Got SSDP Discovery packet from "
                  + packet.getAddress().getHostAddress()
                  + ":"
                  + packet.getPort());
          sendUpnpResponse(responseSocket, packet.getAddress(), packet.getPort());
        }
      }

    } catch (IOException e) {
      log.error("UpnpListener encountered an error. Shutting down", e);
      ConfigurableApplicationContext context =
          (ConfigurableApplicationContext) UpnpListener.this.applicationContext;
      context.close();
    }
    log.info("UPNP Discovery Listener Stopped");
  }
  public void run() {
    while (listen) {
      try {
        byte[] buf = new byte[256];
        byte[] buf2 = new byte[256];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        InetAddress address;
        socket.receive(packet);
        String in = new String(packet.getData(), 0, packet.getLength());
        address = packet.getAddress();
        int port = packet.getPort();
        // newClient = findPort(port, address, newClient);
        String name = findPerson(port, address);
        // System.out.println(name);
        if (in.startsWith("1")) {
          String nama = new String(packet.getData(), 0, packet.getLength());
          nama = nama.substring(1);
          newClient = new Client(packet.getAddress(), packet.getPort(), nama);
          threads.add(newClient);
          String wel =
              "\nWelcome "
                  + newClient.nama
                  + "\n "
                  + "to quit type \"bye\" and to whisper use prefix @name : ";
          buf = (wel).getBytes();
          packet = new DatagramPacket(buf, buf.length, packet.getAddress(), packet.getPort());
          socket.send(packet);
          wel = " enters the room";
          buf = (newClient.nama + wel).getBytes();
          Broadcast(address, port, buf);
        } else if (in.startsWith("@")) {
          // findPort(port, address, newClient);
          Whisper(newClient, packet.getData());
        } else if (in.equals("bye")) {

          String bye = name + " is leaving";
          buf2 = bye.getBytes();
          // packet = new DatagramPacket(buf,buf.length,newClient.address, newClient.port);
          Broadcast(address, port, buf2);

        } else {
          byte[] buf3 = new byte[256];
          String text =
              name + "<broadcast> : " + new String(packet.getData(), 0, packet.getLength());
          buf3 = text.getBytes();
          Broadcast(packet.getAddress(), packet.getPort(), buf3);
        }
      } catch (IOException ex) {
        Logger.getLogger(DatagramServer.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
    socket.close();
  }
  public void run() {
    try {
      byte buf[] = new byte[DNSConstants.MAX_MSG_ABSOLUTE];
      DatagramPacket packet = new DatagramPacket(buf, buf.length);
      while (this._jmDNSImpl.getState() != DNSState.CANCELED) {
        packet.setLength(buf.length);
        this._jmDNSImpl.getSocket().receive(packet);
        if (this._jmDNSImpl.getState() == DNSState.CANCELED) {
          break;
        }
        try {
          if (this._jmDNSImpl.getLocalHost().shouldIgnorePacket(packet)) {
            continue;
          }

          DNSIncoming msg = new DNSIncoming(packet);
          logger.finest("SocketListener.run() JmDNS in:" + msg.print(true));

          this._jmDNSImpl.ioLock();
          try {
            if (msg.isQuery()) {
              if (packet.getPort() != DNSConstants.MDNS_PORT) {
                this._jmDNSImpl.handleQuery(msg, packet.getAddress(), packet.getPort());
              }
              this._jmDNSImpl.handleQuery(msg, this._jmDNSImpl.getGroup(), DNSConstants.MDNS_PORT);
            } else {
              this._jmDNSImpl.handleResponse(msg);
            }
          } finally {
            this._jmDNSImpl.ioUnlock();
          }
        } catch (IOException e) {
          logger.log(Level.WARNING, "run() exception ", e);
        }
      }
    } catch (IOException e) {
      if (this._jmDNSImpl.getState() != DNSState.CANCELED) {
        logger.log(Level.WARNING, "run() exception ", e);
        this._jmDNSImpl.recover();
      }
    }
    // jP: 20010-01-18. Per issue #2933183. If this thread was stopped
    // by closeMulticastSocket, we need to signal the other party via
    // the jmDNS monitor. The other guy will then check to see if this
    // thread has died.
    // Note: This is placed here to avoid locking the IoLock object and
    // 'this' instance together.
    synchronized (this._jmDNSImpl) {
      this._jmDNSImpl.notifyAll();
    }
  }
Beispiel #7
0
  /**
   * Empfangen einer Nachricht ueber UDP
   *
   * @return Referenz auf Nachricht, die empfangen wurde
   * @param timeout Wartezeit in ms
   * @throws IOException
   */
  public Object receive(int timeout) throws IOException, SocketTimeoutException {
    // Maximale Wartezeit fuer Receive am Socket einstellen
    try {
      log.info("RECEIVE MIT TIMEOUT: " + timeout);
      socket.setSoTimeout(timeout);
      // System.out.println("RECEIVE: Maximale Wartezeit: " +
      // timeout +" ms");
    } catch (SocketException e) {
      log.error("RECEIVE: " + "Fehler beim Einstellen der maximalen Wartezeit");
      throw e;
    }

    byte[] bytes = new byte[65527];
    DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
    // System.out.println("VOR: Empfangene Datenlaenge:  " + packet.getLength());
    try {
      // Blockiert nur, bis Timeout abgelaufen ist
      socket.receive(packet);
      log.debug("RECEIVE: Empfangene Datenlaenge:  " + packet.getLength());
      System.out.println("RECEIVE: Empfangene Datenlaenge:  " + packet.getLength());

    } catch (IOException e2) {
      log.error("RECEIVE: " + "Fehler beim Empfangen einer PDU ueber UDP", e2);
      throw e2;
    }

    ByteArrayInputStream bais = new ByteArrayInputStream(packet.getData());
    ObjectInputStream ois = new ObjectInputStream(bais);

    Object pdu;
    try {

      // System.out.println("RECEIVE: " +
      // "Verfuegbare Bytes Inputstream des UDP-Sockets:" +
      // ois.available());

      pdu = ois.readObject();

      remoteAddress = packet.getAddress();
      remotePort = packet.getPort();

      log.debug("RECEIVE: " + packet.getPort() + "->" + socket.getLocalPort());

    } catch (ClassNotFoundException e) {
      log.error("RECEIVE: " + "ClassNotFoundException:", e);
      return null;
    }

    log.info("RECEIVE MIT TIMEOUT ENDE: " + timeout);
    return pdu;
  }
Beispiel #8
0
  public static void main(String[] args) throws IOException {
    /* 接受发过来的数据 */

    // 创建upd socket服务对象
    DatagramSocket ds = new DatagramSocket(10039);

    // 创建数据包,用于存储接收到的数据
    byte[] bbuf = new byte[1024];
    DatagramPacket dp = new DatagramPacket(bbuf, bbuf.length);

    // 用socket对象的receive方法将接收到的数据存储到数据包中
    ds.receive(dp);

    // 获取ip
    String ip = dp.getAddress().getHostAddress();
    int port = dp.getPort();

    // 获取数据内容
    byte[] data = dp.getData();
    String text = new String(data, 0, dp.getLength());

    System.out.println(ip + ":" + port + ":" + text);

    ds.close();
  }
  public List<EventReply> receive() throws IOException {
    byte[] buf = new byte[0xff];
    DatagramPacket packet = new DatagramPacket(buf, 0, 0xff);
    m_dgSocket.receive(packet);
    byte[] data = packet.getData();
    //		System.out.println("receive data is : "+new String(data,"utf-8"));
    StringReader reader = new StringReader(new String(data, 0, packet.getLength(), "utf-8"));
    EventReceipt receipt = null;
    try {

      receipt = (EventReceipt) Unmarshaller.unmarshal(EventReceipt.class, reader);
    } catch (MarshalException e) {
      e.printStackTrace();
    } catch (ValidationException e) {
      e.printStackTrace();
    }

    InetAddress remoteAddr = packet.getAddress();
    int port = packet.getPort();
    List<EventReply> replys = new ArrayList<EventReply>();
    if (receipt != null) {
      String[] uuids = receipt.getUuid();
      for (String uuid : uuids) {
        EventReply reply = new EventReply(remoteAddr, port, uuid);
        replys.add(reply);
      }
    }
    return replys;
  }
  public void run() {
    while (true) {
      try {
        // System.out.println("Waiting for client on port " +serverSocket.getLocalPort() + "...");
        byte[] receiveBuffer = new byte[512];
        DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
        UDPserverSocket.receive(receivePacket);
        System.out.println(
            "Request received from "
                + receivePacket.getSocketAddress()
                + ":"
                + receivePacket.getPort());

        // Start new 'Servant' thread and make it serve the peer
        new Servant(receivePacket, UDPserverSocket).start();
        // socketFromPeer.close();

      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }
Beispiel #11
0
  public static void doEcho(int port) throws IOException {
    byte[] buf = new byte[BUF_SIZE];
    DatagramPacket packet = new DatagramPacket(buf, buf.length);
    DatagramSocket sock = new DatagramSocket(port);

    System.out.println(
        "Starting UDP echo on"
            + sock.getLocalAddress().getHostAddress()
            + ":"
            + sock.getLocalPort());
    while (true) {
      try {
        sock.receive(packet);
        sock.send(packet);
        System.out.print(
            "UDP From: "
                + packet.getAddress().getHostAddress()
                + ":"
                + packet.getPort()
                + "\n"
                + new String(packet.getData(), 0, packet.getLength())
                + "\n");
        System.out.flush();

        packet.setLength(buf.length);
        // packet = new DatagramPacket(buf,buf.length);
      } catch (IOException io_ex) {
      }
    }
  }
  /**
   * Copies the properties of a specific <tt>DatagramPacket</tt> to another <tt>DatagramPacket</tt>.
   * The property values are not cloned.
   *
   * @param src the <tt>DatagramPacket</tt> which is to have its properties copied to <tt>dest</tt>
   * @param dest the <tt>DatagramPacket</tt> which is to have its properties set to the value of the
   *     respective properties of <tt>src</tt>
   */
  public static void copy(DatagramPacket src, DatagramPacket dest) {
    synchronized (dest) {
      dest.setAddress(src.getAddress());
      dest.setPort(src.getPort());

      byte[] srcData = src.getData();

      if (srcData == null) dest.setLength(0);
      else {
        byte[] destData = dest.getData();

        if (destData == null) dest.setLength(0);
        else {
          int destOffset = dest.getOffset();
          int destLength = destData.length - destOffset;
          int srcLength = src.getLength();

          if (destLength >= srcLength) destLength = srcLength;
          else if (logger.isLoggable(Level.WARNING)) {
            logger.log(Level.WARNING, "Truncating received DatagramPacket data!");
          }
          System.arraycopy(srcData, src.getOffset(), destData, destOffset, destLength);
          dest.setLength(destLength);
        }
      }
    }
  }
Beispiel #13
0
  public void run() {

    boolean bContinue = true;

    while (bContinue) {
      try {
        byte[] buf = new byte[256];

        DatagramPacket packet = new DatagramPacket(buf, buf.length);

        /** wait here for incoming data */
        socket.receive(packet);

        /** received data */
        InetAddress address = packet.getAddress();
        int port = packet.getPort();
        byte[] data = packet.getData();

        /** deserialize the data into a String object (what we expect) */
        ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data));
        String sData = (String) in.readObject();
        in.close();

        String sText = ui.getTextIncoming().getText();
        sText += address.getHostAddress() + ":" + port + "  " + sData + "\n";
        ui.getTextIncoming().setText(sText);

      } catch (IOException e) {
        e.printStackTrace();
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }
    }
  }
Beispiel #14
0
  public void startServer() {

    try {
      serverSocket = MyUtil.getSocket();
      log.info(MyUtil.getMyIPAddress());
      log.info(MyUtil.getPort());
      byte[] receiveData = new byte[1024];
      byte[] sendData = new byte[1024];
      while (true) {
        log.info("RPCServer.main() Running");
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        serverSocket.receive(receivePacket);
        InetAddress IPAddress = receivePacket.getAddress();
        int port = receivePacket.getPort();
        log.info(
            "============================================Packet Received from :"
                + IPAddress.getHostAddress());
        log.info("=============================================Packet Recieved from Port:" + port);
        sendData = proccessRequest(receiveData);
        log.info(
            "=============================================Sending Response :"
                + new String(sendData));
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
        serverSocket.send(sendPacket);
      }
    } catch (SocketException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Beispiel #15
0
 /** Receive loop for private messaqes. Can be stopped with {@link #setRunning(boolean)} */
 private void receivePrivateMessages() {
   while (isRunning()) {
     try {
       final byte[] buf = new byte[BUFFER_SIZE];
       final DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
       if (LOG.isDebugEnabled()) {
         LOG.debug(
             "Waiting for private message, listening on port " + privateSocket.getLocalPort());
       }
       privateSocket.receive(receivePacket); // wait for a packet
       final String data = toString(receivePacket);
       if (LOG.isDebugEnabled()) {
         LOG.debug("Got a private message: " + data);
       }
       if (LOG.isDebugEnabled()) {
         LOG.debug(
             "Received "
                 + data
                 + " from "
                 + receivePacket.getAddress()
                 + ":"
                 + receivePacket.getPort()
                 + ".");
       }
       processPrivateMessage(data);
     } catch (IOException e) {
       LOG.error(BUNDLE_MARKER, e.toString(), e);
     }
   }
   if (LOG.isDebugEnabled()) {
     LOG.debug("Stopped listening to private messages.");
   }
 }
  private void listen() throws Exception {
    System.out.println("Listening on port: " + serverPort);
    // Initialize socket
    socket = new DatagramSocket(serverPort);

    // While running
    while (run) {

      // Wait for handshake
      packet = new DatagramPacket(response, response.length);
      socket.receive(packet); // Blocking
      // System.out.println("RT: got packet");
      Packet p = new Packet(packet.getData());

      if (p.isHandshake()) {
        // System.out.println("RT: is handshake");
        // Get client connection info
        InetAddress IPAddress = packet.getAddress();
        int port = packet.getPort();

        // Process handshake
        processHandshake(p, IPAddress, port);

        // Get message
        MyMessage message = getMessage();

        if (message != null) {
          rc.rreceive(message);
        }
      }
    }
  }
  /** Wait until there more data to process */
  public synchronized void sendAndWaitUntilNextUdpMessage(UDPMessage message) throws Exception {
    byte[] response = Serializer.serialize(message);
    DatagramPacket reply =
        new DatagramPacket(
            response, response.length, receivedDatagram.getAddress(), receivedDatagram.getPort());
    try {
      // lock to wait for next DatagramPacket which is the answer of this reply
      waitForNextDatagram = true;

      aSocket.send(reply);

      // wait for the response before continuing
      while (waitForNextDatagram) {
        try {
          this.wait();
        } catch (Exception e) {

        }
      }
      waitForNextDatagram = true;
    } catch (Exception e) {
      // handled by the parent function
      throw e;
    }
  }
Beispiel #18
0
 public static void main(String[] args) throws IOException {
   String strSend = "Hello ANDROID";
   byte[] buf = new byte[1024];
   // 服务端在3000端口监听接收到的数据
   DatagramSocket ds = new DatagramSocket(3000);
   // 接收从客户端发送过来的数据
   DatagramPacket dpReceive = new DatagramPacket(buf, 1024);
   System.out.println("server is on,waiting for client to send data......");
   boolean f = true;
   while (f) {
     // 服务器端接收来自客户端的数据
     ds.receive(dpReceive);
     System.out.println("server received data from client:");
     String strReceive =
         new String(dpReceive.getData(), 0, dpReceive.getLength())
             + " from "
             + dpReceive.getAddress().getHostAddress()
             + ":"
             + dpReceive.getPort();
     System.out.println(strReceive);
     // 数据发动到客户端的3000端口
     DatagramPacket dpSend =
         new DatagramPacket(strSend.getBytes(), strSend.length(), dpReceive.getAddress(), 9000);
     ds.send(dpSend);
     // 由于dp_receive在接收了数据之后,其内部消息长度值会变为实际接收的消息的字节数,
     // 所以这里要将dp_receive的内部消息长度重新置为1024
     dpReceive.setLength(1024);
   }
   ds.close();
 }
  // usado por quem vai receber o arquivo
  public miniSocket(
      int porta_servidor, InetAddress endereco_servidor, FileOutputStream arquivo_receber)
      throws IOException {
    this.arquivo_receber = arquivo_receber;
    real_socket = new DatagramSocket();
    this.server_port = porta_servidor;
    this.server_adress = endereco_servidor;
    DatagramPacket receiver =
        new DatagramPacket(new byte[Pacote.head_payload], Pacote.head_payload);
    while (!connect.get()) {

      for (int i = 0; i < max_win; i++) {
        real_socket.send(
            new DatagramPacket(SYN_BYTE, Pacote.head_payload, endereco_servidor, porta_servidor));
      }
      new Timer().scheduleAtFixedRate(new try_connect(), 300, 300);
      real_socket.receive(receiver);
      if (receiver.getAddress().equals(endereco_servidor) && receiver.getPort() == porta_servidor) {
        connect.set(true);
      } else {
        System.out.println("Conexao comprometida....");
      }
    }

    new Thread(new Receiver()).start();
  }
  public static void main(String args[]) {
    DatagramSocket skt = null;
    try {
      skt = new DatagramSocket(6789);
      byte[] buffer = new byte[1000];
      while (true) {
        DatagramPacket request = new DatagramPacket(buffer, buffer.length);
        skt.receive(request);
        System.out.println("Data received from client");
        System.out.println(new String(request.getData()));
        Thread.sleep(15000);

        String[] arrayMsg = (new String(request.getData())).split(" ");

        System.out.println(arrayMsg[0] + "server processed");

        byte[] sendMsg = (arrayMsg[0] + "server processed").getBytes();

        DatagramPacket reply =
            new DatagramPacket(sendMsg, sendMsg.length, request.getAddress(), request.getPort());

        System.out.println("sending data from server to client");
        Thread.sleep(15000);
        ;
        skt.send(reply);
      }
    } catch (Exception e) {

    }
  }
Beispiel #21
0
 public static void displayInfo(DatagramPacket packet) {
   System.out.println("Received: ");
   System.out.println("IP Address: " + packet.getAddress());
   System.out.println("Port: " + packet.getPort());
   System.out.println("Date: " + new Date());
   System.out.println("Message: " + new String(packet.getData()));
 }
  @Override
  public SctpChannel accept()
      throws IOException, SctpException, InvalidKeyException, NoSuchAlgorithmException {
    logger.setLevel(Level.INFO);

    DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
    SctpPacket packet = null;
    while (true) {
      serverSocket.receive(receivePacket);
      try {
        packet = new SctpPacket(buffer, 0, receivePacket.getLength());
      } catch (SctpException e) {
        logger.log(Level.WARNING, e.getMessage());
        continue;
      }

      logger.log(Level.INFO, "receive new packet");

      InetSocketAddress address =
          new InetSocketAddress(receivePacket.getAddress(), receivePacket.getPort());
      packet.apply(address, this);

      Association association = pendingAssociations.get(address);
      if (association != null && association.getState() == State.ESTABLISHED) {
        return new SctpChannel(association);
      }
    }
  }
  public void runReceivingDispather() {
    int i = 0;

    // change this to 2 loops
    while (i < 2) {
      //  receiveData  = new byte[12];

      receivePacket = new DatagramPacket(receiveData, receiveData.length);

      System.out.println("Dispatcher");
      try {
        serverSocket.receive(receivePacket);
      } catch (IOException ex) {
        Logger.getLogger(DispatcherReceiver.class.getName()).log(Level.SEVERE, null, ex);
      }

      String temp = this.assignReceiver(receivePacket);

      // returns the port number for receiver server
      sendData = temp.getBytes();

      InetAddress address = receivePacket.getAddress();
      int tempPort = receivePacket.getPort();

      sendPacket = new DatagramPacket(sendData, sendData.length, address, tempPort);
      try {
        serverSocket.send(sendPacket);
      } catch (IOException ex) {
        Logger.getLogger(DispatcherReceiver.class.getName()).log(Level.SEVERE, null, ex);
      }

      i++;
    }
  }
Beispiel #24
0
  public void run() throws SocketException {
    DatagramSocket socket = null;
    try {
      socket = new DatagramSocket(53);

      logger.info("Listening on DNS Port(53)");

      int ECHOMAX = 2048;

      DatagramPacket packet = new DatagramPacket(new byte[ECHOMAX], ECHOMAX);

      while (true) {
        try {
          socket.receive(packet);
        } catch (IOException e) {
          e.printStackTrace();
        }
        byte[] data = packet.getData();
        int length = packet.getLength();
        byte[] d = new byte[length];
        System.arraycopy(data, 0, d, 0, length);
        byte[] response = parse(d);

        DatagramPacket re =
            new DatagramPacket(response, response.length, packet.getAddress(), packet.getPort());
        re.setData(response);
        socket.send(re);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Beispiel #25
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();
      }
    }
  }
  public void run() {

    while (moreQuotes) {
      try {
        byte[] buf = new byte[256];

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

        // figure out response
        String dString = null;
        if (in == null) dString = new Date().toString();
        else dString = getNextQuote();
        buf = dString.getBytes();

        // send the response to the client at "address" and "port"
        InetAddress address = packet.getAddress();
        int port = packet.getPort();
        packet = new DatagramPacket(buf, buf.length, address, port);
        socket.send(packet);
      } catch (IOException e) {
        e.printStackTrace();
        moreQuotes = false;
      }
    }
    socket.close();
  }
Beispiel #27
0
  public void run() {

    try {
      while (running) {
        byte[] sendClientData = new byte[512];
        byte[] sendServerData = new byte[512];
        byte[] receiveClientData = new byte[512];
        byte[] receiveServerData = new byte[512];

        DatagramPacket receiveClientPacket = receivePacket(receiveClientData, receiveSocket);
        receiveClientPacket.getLength();
        // find port used by client
        int clientPort = receiveClientPacket.getPort();

        DatagramSocket hostSocket = new DatagramSocket();

        sendServerData = receiveClientPacket.getData();
        sendPacket(sendServerData, serverIPAddress, ServerPort, hostSocket);

        DatagramPacket receiveServerPacket = receivePacket(receiveServerData, hostSocket);
        if (receiveServerPacket.getData()[0] == 1) {
          running = false;
        }
        sendClientData = receiveServerPacket.getData();
        sendPacket(sendClientData, clientIPAddress, clientPort, hostSocket);

        hostSocket.close();
      }
      receiveSocket.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Beispiel #28
0
  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();
      }
    }
  }
Beispiel #29
0
    public void run() {
      boolean running = true;

      DatagramPacket msg = new DatagramPacket(b, b.length);

      logReader.debug("Reader running (Multicast=" + (sock instanceof MulticastSocket) + ").");

      while (running) {
        try {
          sock.receive(msg);

          if (debugFull) logReader.debug(":run: PtP datagram received. Size = " + msg.getLength());

          if ((ignoreSource != null)
              && (ignoreSource.getPort() == msg.getPort())
              && (ignoreSource.getAddress().equals(msg.getAddress()))) {
            if (debugFull) logReader.debug(":run: Ignored Last received message");
          } else receiveFormatSend(msg);

        } catch (SocketTimeoutException ste) {
          //        	ste.printStackTrace();
        } catch (IOException e) {
          System.err.println("[UdpSimpleSession:reader:run] IOException: " + e.getMessage());
        }

        synchronized (this) {
          if (terminate) running = false;
        }
      }
    }
Beispiel #30
0
  public static void main(String args[]) throws Exception {

    String serverHostname = args[0];
    int portNumber = Integer.parseInt(args[1]);

    try {
      BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

      DatagramSocket clientSocket = new DatagramSocket();

      InetAddress IPAddress = InetAddress.getByName(serverHostname);
      System.out.println("Attempting to connect to " + IPAddress + ") via UDP port " + portNumber);
      System.out.println("Enter \"Quit\" to exit program");

      while (true) {
        byte[] sendData = new byte[1024];
        byte[] receiveData = new byte[1024];

        System.out.print("Enter Message: ");
        String sentence = inFromUser.readLine();

        if (sentence.equals("Quit")) break;

        sendData = sentence.getBytes();

        System.out.println("Sending data to " + sendData.length + " bytes to server.");
        DatagramPacket sendPacket =
            new DatagramPacket(sendData, sendData.length, IPAddress, portNumber);

        clientSocket.send(sendPacket);

        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

        System.out.println("Waiting for return packet");
        clientSocket.setSoTimeout(10000);

        try {
          clientSocket.receive(receivePacket);
          String modifiedSentence = new String(receivePacket.getData());

          InetAddress returnIPAddress = receivePacket.getAddress();

          int port = receivePacket.getPort();

          System.out.println("From server at: " + returnIPAddress + ":" + port);
          System.out.println("Message: " + modifiedSentence);
        } catch (SocketTimeoutException ste) {
          System.out.println("Timeout Occurred: Packet assumed lost");
        }
        System.out.print("\n");
      }

      clientSocket.close();
    } catch (UnknownHostException ex) {
      System.err.println(ex);
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }