示例#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();
      }
    }
  }
示例#2
0
  /**
   * Debug function
   *
   * @param log_tag
   * @param identifier part of application which called this
   * @param dp UDP datagram
   */
  public static void printPackageInfo(String log_tag, String identifier, DatagramPacket dp) {

    logByte(log_tag, "Content: " + identifier + "\n", dp.getData(), dp.getLength());
    Log.d(log_tag, Boolean.toString(dp.getAddress().isMulticastAddress()));
    Log.d(log_tag, dp.getAddress().getHostAddress());
    Log.d(log_tag, dp.getSocketAddress().toString());
  }
示例#3
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();
 }
示例#4
0
  @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) {

      }
    }
  }
示例#5
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);
    }
  }
  @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");
  }
示例#7
0
  @Override
  public void run() {
    try {

      DatagramSocket dsocket = new DatagramSocket(portServer);
      DatagramSocket ssocket = new DatagramSocket();

      byte[] buffer = new byte[1024];

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

      SpeexDecoder speexDecoder = new SpeexDecoder();
      speexDecoder.init(0, 8000, 1, false);

      ByteBuffer storeBuffer = ByteBuffer.allocate(115000);
      int arrayLength;
      do {
        dsocket.receive(packet);

        arrayLength = packet.getLength();
        speexDecoder.processData(packet.getData(), 0, packet.getData().length);

        byte data[] = new byte[speexDecoder.getProcessedDataByteSize()];
        speexDecoder.getProcessedData(data, 0);

        System.out.println("Data length: " + data.length);

        storeBuffer.put(data);
        if (storeBuffer.position() > 114000) {
          String host = Mapping.getDestination(packet.getAddress().toString().substring(1));
          System.out.println("Client IP : " + packet.getAddress().toString());

          AudioInputStream stream = AudioUtils.soundBytesToAudio(storeBuffer.array());
          storeBuffer.clear();

          String fileName = "./resources/tmp/" + NameGenerator.getName() + ".wav";

          AudioUtils.saveAudioStreamToFile(stream, fileName);
          stream.close();

          String[] result = RecognitionEngine.recogniseAudio(fileName);

          ssocket.send(
              new DatagramPacket(
                  result[0].getBytes(),
                  result[0].getBytes().length,
                  InetAddress.getByName(host),
                  portClient));
        }
      } while (arrayLength > 0);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  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 String toString() {
    int size = 0;
    String type = "NONE";
    String addr = null;

    if (packet != null && packet.getAddress() != null && packet.getLength() > 0) {
      type = RobocolParsable.MsgType.fromByte(packet.getData()[0]).name();
      size = packet.getLength();
      addr = packet.getAddress().getHostAddress();
    }

    return String.format("RobocolDatagram - type:%s, addr:%s, size:%d", type, addr, size);
  }
 /** {@inheritDoc} */
 public void run() {
   final int MULTICAST_PORT = configuration.getMulticastPort();
   final String MULTICAST_ADDRESS = configuration.getMulticastAddress();
   String multicastLocation = MULTICAST_ADDRESS + ":" + MULTICAST_PORT;
   MulticastSocket socket = null;
   InetAddress address = null;
   try {
     socket = new MulticastSocket(MULTICAST_PORT);
     address = InetAddress.getByName(MULTICAST_ADDRESS);
     logger.info("Created IP discover multicast server !");
   } catch (IOException e) {
     logger.error("Can't create multicast socket on " + multicastLocation, e);
   }
   try {
     socket.joinGroup(address);
     logger.info("Joined a group : " + multicastLocation);
   } catch (IOException e) {
     logger.error("Can't join group of " + multicastLocation, e);
   }
   byte[] buf = new byte[512];
   DatagramPacket packet = new DatagramPacket(buf, buf.length);
   while (true) {
     try {
       logger.info("Listening on  " + multicastLocation);
       socket.receive(packet);
       logger.info(
           "Received an IP auto-discovery request from " + packet.getAddress().getHostAddress());
     } catch (IOException e) {
       logger.error("Can't receive packet on " + MULTICAST_ADDRESS + ":" + MULTICAST_PORT, e);
     }
     sendLocalIPBack(packet);
   }
 }
示例#11
0
 // ------------------------------------------------------------
 private void extractPacketData(StorageServer serv, DatagramPacket receivePacket)
     throws IOException {
   try {
     byte[] temp = new byte[4];
     System.arraycopy(receivePacket.getData(), 3, temp, 0, 4);
     serv.IP = InetAddress.getByAddress(temp).getHostAddress();
     // System.out.println("serv.ip: " + serv.IP);
     // serv.IP = receivePacket.getAddress().getHostAddress();
     // System.out.println("serv.ip: " + serv.IP);
     // System.out.println("inetaddress.getbyname() : " +
     // InetAddress.getByName(gwIP))
     /*
      * serv.IP = String.valueOf(receivePacket.getData()[3]) + "." +
      * String.valueOf(receivePacket.getData()[4]) + "." +
      * String.valueOf(receivePacket.getData()[5]) + "." +
      * String.valueOf(receivePacket.getData()[6]);
      */ serv.port = (int) (receivePacket.getData()[7] << 8) + receivePacket.getData()[8];
     System.out.println("Connecting to: " + serv.IP + ":" + serv.port);
     Socket s = new Socket(InetAddress.getByName(serv.IP), serv.port);
     serv.sock = s;
   } catch (IOException e) {
     System.out.println(
         "BIG PROBLEM HERE BECAUSE YOU CANNOT CONNECT " + "BACK!!!!!!!! Trying other address");
     try {
       serv.IP = receivePacket.getAddress().getHostAddress();
       System.out.println("Connecting to: " + serv.IP + ":" + serv.port);
       Socket s = new Socket(InetAddress.getByName(serv.IP), serv.port);
       serv.sock = s;
     } catch (IOException f) {
       System.out.println("cannot connect here aswell\n");
       throw new IOException(f);
     }
   }
 }
示例#12
0
 // Methods for the treatment of the different message types
 private void loginMessageTreatment() throws IncorrectMessageException {
   String content = message.getText().trim();
   if (content != null && !content.contains("&")) {
     if (this.userList.getUserByNick(content) != null) {
       // The nick already exist (send 301)
       String response = new Integer(Message.ERROR_MESSAGE_EXISTING_NICK).toString();
       sendDatagram(
           new User(
               null,
               messageToProcces.getAddress().getHostAddress(),
               this.messageToProcces.getPort()),
           response);
       // Comprobamos el nick pero, ¿Y si ya hay un usuario en esa IP???
     } else {
       // Everything correct, send ACK
       User newUser =
           new User(
               content,
               this.messageToProcces.getAddress().getHostAddress(),
               this.messageToProcces.getPort());
       userList.add(newUser);
       String response =
           new Integer(Message.SERVER_MESSAGE_CONNECTED).toString() + this.userList.toString();
       sendDatagram(newUser, response);
     }
   } else {
     throw new IncorrectMessageException(
         "The Login message is not correct: '" + content.toString() + "'");
   }
 }
示例#13
0
  @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);
      }
    }
  }
示例#14
0
文件: Usr.java 项目: qoopooh/try_git
  public static List<Usr> getList() throws IOException {
    byte[] host_ip = InetAddress.getLocalHost().getAddress();
    DatagramSocket serverSocket = new DatagramSocket(UDP_PORT);
    byte[] buf = BROADCAST_MSG.getBytes();
    InetAddress address = InetAddress.getByName(ALL_IP);
    DatagramPacket packet = new DatagramPacket(buf, buf.length, address, UDP_PORT);
    serverSocket.send(packet);
    serverSocket.setSoTimeout(SOCKET_TIMEOUT); // set the timeout in millisecounds.

    ArrayList<Usr> out = new ArrayList<Usr>();
    while (true) {
      try {
        byte[] rcv = new byte[32];
        packet = new DatagramPacket(rcv, rcv.length);
        serverSocket.receive(packet);
        byte[] ip = packet.getAddress().getAddress();
        if (Arrays.equals(ip, host_ip)) continue;
        Usr usr = new Usr(packet.getData());
        out.add(usr);
      } catch (SocketTimeoutException e) {
        break;
      }
    }

    serverSocket.close();
    return out;
  }
示例#15
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;
        }
      }
    }
示例#16
0
  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();
  }
示例#17
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.");
   }
 }
示例#18
0
  public void send(byte[] buf, DatagramPacket dp) throws InterruptedException, IOException {
    StringBuilder source = new StringBuilder();
    source.append(dp.getAddress());
    String dataType = type;
    byte[] trimmedBuf = Arrays.copyOf(buf, dp.getLength());
    String rawPRI = new String(trimmedBuf, 1, 4, Charset.forName("UTF-8"));
    int i = rawPRI.indexOf(">");
    if (i <= 3 && i > -1) {
      String priorityStr = rawPRI.substring(0, i);
      int priority = 0;
      int facility = 0;
      try {
        priority = Integer.parseInt(priorityStr);
        facility = (priority >> 3) << 3;
        facility = facility / 8;
        dataType = facilityMap.get(facility);
      } catch (NumberFormatException nfe) {
        log.warn("Unsupported format detected by SyslogAdaptor:" + Arrays.toString(trimmedBuf));
      }
    }

    bytesReceived += trimmedBuf.length;
    Chunk c =
        new ChunkImpl(dataType, source.toString(), bytesReceived, trimmedBuf, SyslogAdaptor.this);
    dest.add(c);
  }
示例#19
0
  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;
  }
示例#20
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) {
      }
    }
  }
 public void run() {
   while (running) {
     try {
       // create a buffer for the datagram packet
       byte[] buf = new byte[XMOSLedTilePacketPayload.MAX_PAYLOAD_SIZE];
       // receive a packet
       DatagramPacket packet = new DatagramPacket(buf, buf.length);
       socket.receive(packet);
       LOGGER.debug("Packet received {}", packet);
       // analyze the data if it is a XMOS packet
       byte[] data = packet.getData();
       // we must have at least XMOS + package ID
       if (data.length > 5) {
         byte[] magicString = new byte[MAGIC_STRING.length()];
         System.arraycopy(data, 0, magicString, 0, MAGIC_STRING.length());
         String packageMagicString = new String(magicString);
         if (MAGIC_STRING.equals(packageMagicString)) {
           LOGGER.info(
               "Retrieved a XMOS package from {}:{}",
               packet.getAddress(),
               packet.getSocketAddress());
           addPacket(packet);
         }
       }
     } catch (IOException e) {
       LOGGER.error("Unable to retrieve packet, ignoring it.", e);
     }
   }
 }
示例#22
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()));
 }
  /** 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;
    }
  }
示例#24
0
 public void sendConfiguration(Biasgen biasgen) throws HardwareInterfaceException {
   if (!isOpen()) {
     throw new HardwareInterfaceException("not open");
   }
   int MAX_COMMAND_LENGTH_BYTES = 256;
   for (Pot p : getBiasgen().getPotArray().getPots()) {
     UDP_VPot vp = (UDP_VPot) p;
     try {
       String s = vp.getCommandString();
       byte[] b = s.getBytes(); // s.getBytes(Charset.forName("US-ASCII"));
       socket.send(new DatagramPacket(b, b.length, client));
       DatagramPacket packet =
           new DatagramPacket(new byte[MAX_COMMAND_LENGTH_BYTES], MAX_COMMAND_LENGTH_BYTES);
       socket.receive(packet);
       ByteArrayInputStream bis;
       BufferedReader reader =
           new BufferedReader(
               new InputStreamReader(
                   (bis = new ByteArrayInputStream(packet.getData(), 0, packet.getLength()))));
       String line = reader.readLine(); // .toLowerCase();
       log.info("response from " + packet.getAddress() + " : " + line);
       //                    System.out.println(line); // debug
     } catch (SocketTimeoutException to) {
       log.warning("timeout on waiting for command response on datagram control socket");
     } catch (Exception ex) {
       throw new HardwareInterfaceException(
           "while sending biases to " + client + " caught " + ex.toString());
     }
   }
 }
示例#25
0
  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);
        }
      }
    }
  }
  /**
   * Parse a received packet, and notify the main thread if valid.
   *
   * @param packet The locally-received DatagramPacket
   */
  private void handleResponsePacket(DatagramPacket packet) {
    String strPacket = new String(packet.getData(), 0, packet.getLength());
    String tokens[] = strPacket.trim().split("\\s+");

    if (tokens.length != 3) {
      Log.w(LOG_TAG, "Malformed response: expected 3 tokens, got " + tokens.length);
      return;
    }

    BroadcastAdvertisement advert;
    try {
      String serviceType = tokens[0];
      if (!serviceType.equals(DESIRED_SERVICE)) {
        return;
      }
      String serviceName = tokens[1];
      int port = Integer.parseInt(tokens[2]);
      InetAddress addr = packet.getAddress();
      Log.v(LOG_TAG, "Broadcast response: " + serviceName + ", " + addr + ", " + port);
      advert = new BroadcastAdvertisement(serviceName, addr, port);
    } catch (NumberFormatException e) {
      return;
    }

    Message message = mHandler.obtainMessage(DeviceFinder.BROADCAST_RESPONSE, advert);
    mHandler.sendMessage(message);
  }
示例#27
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();
      }
    }
  }
示例#28
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();
    }
  }
示例#29
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();
  }
 private void listenForDatabaseServers() {
   if (this.listeningSocket != null) {
     byte[] buffer = new byte[100];
     DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
     while (this.running && this.dbServers.isEmpty()) {
       try {
         this.listeningSocket.receive(packet);
         InetAddress address = packet.getAddress();
         // System.out.println("Discovered server at " + address);
         if (!this.dbServers.contains(address)) {
           this.dbServers.add(address);
         }
         Thread.sleep(500);
       } catch (IOException e) {
         System.err.println("Failed to read socket " + e.getMessage());
       } catch (InterruptedException e) {
         e.printStackTrace();
       } finally {
         this.listeningSocket.close();
       }
     }
     // System.err.println("Finished searching, found " + this.dbServers.size() + " Server");
   } else {
     // System.err.println("No listening socket available");
   }
 }