コード例 #1
1
ファイル: UDPClient.java プロジェクト: itu-cstp/MDS04
  public static void main(String[] args) throws IOException, InterruptedException {
    boolean running = true;
    // udp protocol over a socket.
    DatagramSocket socket = new DatagramSocket();

    while (running) {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

      String line = br.readLine();
      String[] inputs = line.split(" ");

      if (inputs.length < 2) {
        System.out.println("Usage: username command id");
        socket.close();
        return;
      }

      byte[] byteArr = (inputs[0] + " " + inputs[1] + " " + inputs[2]).getBytes();

      // send request
      byte[] buf = new byte[256];
      InetAddress address = InetAddress.getByName("localhost");
      DatagramPacket packet = new DatagramPacket(byteArr, byteArr.length, address, 4445);
      socket.send(packet);

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

      // display response
      String received = new String(packet.getData(), 0, packet.getLength());
      System.out.println("From server: " + received);
    }
    //   socket.close();
  }
コード例 #2
0
  /**
   * 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);
        }
      }
    }
  }
コード例 #3
0
  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) {

    }
  }
コード例 #4
0
    public void run() {
      active = true;

      byte[] b = new byte[PACKET_LENGTH];
      DatagramPacket p = new DatagramPacket(b, b.length);

      while (active) {
        try {
          socket.receive(p);

          // this string constructor which accepts a charset throws an exception if it is
          // null
          if (encoding == null) {
            handlerThread.append(new String(p.getData(), 0, p.getLength()));
          } else {
            handlerThread.append(new String(p.getData(), 0, p.getLength(), encoding));
          }
        } catch (SocketException se) {
          // disconnected
        } catch (IOException ioe) {
          ioe.printStackTrace();
        }
      }

      getLogger().debug("{}'s thread is ending.", MulticastReceiver.this.getName());
    }
コード例 #5
0
ファイル: Host.java プロジェクト: ratminer/TFTP
  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();
    }
  }
コード例 #6
0
ファイル: Blue.java プロジェクト: wrigh182/udpchat
  public static void main(String args[]) throws Exception {

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

    DatagramSocket clientSocket = new DatagramSocket();

    InetAddress IPAddress = InetAddress.getByName("192.168.1.16");

    byte[] sendData = new byte[1024];
    byte[] receiveData = new byte[1024];

    String sentence = new String("HELLO");
    sendData = sentence.getBytes();
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
    clientSocket.send(sendPacket);
    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
    clientSocket.receive(receivePacket);
    sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
    if (sentence.equals("##100##")) {
      System.out.println(sentence + ": Waiting for Red.");
    }
    while (!sentence.equals("##200##")) {
      try {
        receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);
        sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
      } catch (Exception e) {

      }
    }
    if (sentence.equals("##200##")) {
      System.out.println(sentence + ": Red and Blue are connected");
    }

    while (true) {
      receiveData = new byte[1024];
      receivePacket = new DatagramPacket(receiveData, receiveData.length);

      clientSocket.receive(receivePacket);

      sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());

      if (sentence.equals("##300##")) {
        break;
      }

      System.out.println("RED: " + sentence);

      sentence = inFromUser.readLine();
      sendData = sentence.getBytes();
      sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);

      clientSocket.send(sendPacket);
    }
    System.out.println(sentence + ": Disconnected.");
    clientSocket.close();
  }
コード例 #7
0
  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();
  }
コード例 #8
0
ファイル: UDPEcho.java プロジェクト: jmcabandara/OneSwarm
  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) {
      }
    }
  }
コード例 #9
0
ファイル: MPING.java プロジェクト: flashboss/JGroups
  public void run() {
    final byte[] receive_buf = new byte[65535];
    DatagramPacket packet = new DatagramPacket(receive_buf, receive_buf.length);
    byte[] data;
    ByteArrayInputStream inp_stream;
    DataInputStream inp = null;
    Message msg;

    while (mcast_sock != null && receiver != null && Thread.currentThread().equals(receiver)) {
      packet.setData(receive_buf, 0, receive_buf.length);
      try {
        mcast_sock.receive(packet);
        data = packet.getData();
        inp_stream = new ExposedByteArrayInputStream(data, 0, data.length);
        inp = new DataInputStream(inp_stream);
        msg = new Message();
        msg.readFrom(inp);
        up(new Event(Event.MSG, msg));
      } catch (SocketException socketEx) {
        break;
      } catch (Throwable ex) {
        log.error("failed receiving packet (from " + packet.getSocketAddress() + ")", ex);
      } finally {
        Util.close(inp);
      }
    }
    if (log.isTraceEnabled()) log.trace("receiver thread terminated");
  }
コード例 #10
0
  /**
   * Attempts to log a client in using the authentication server. Authentication server needs to run
   * on the same host as the file server.
   *
   * @throws IOException Error reading from socket.
   */
  private void login() throws IOException {
    // set up required variables
    DatagramSocket clientSocket = new DatagramSocket();
    InetAddress authServerIP =
        InetAddress
            .getLocalHost(); // because authentication server runs on same host as file server
    byte[] dataToSend;
    byte[] receivedData = new byte[BUFFER_SIZE];

    // get username and password
    String userName = inFromClient.readLine().trim(); // get username
    String password = inFromClient.readLine().trim(); // get password
    dataToSend = new String(userName + " " + password).getBytes();

    // send the username and password for processing by authentication server
    DatagramPacket packetToSend =
        new DatagramPacket(dataToSend, dataToSend.length, authServerIP, AUTHENTICATION_PORT);
    clientSocket.send(packetToSend);

    // receive the response from the authentication server
    DatagramPacket receivedPacket = new DatagramPacket(receivedData, receivedData.length);
    clientSocket.receive(receivedPacket);
    String receivedString = new String(receivedPacket.getData()).trim();
    receivedData = receivedString.getBytes();
    if (receivedString.equals("yes")) {
      outToClient.writeBytes(receivedString); // successful login
    } else {
      outToClient.writeBytes("no"); // unsuccessful login
    }
  }
コード例 #11
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();
      }
    }
  }
コード例 #12
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);
        }
      }
    }
  }
コード例 #13
0
  public void run() {
    while (true) {
      try {
        DatagramSocket ClientSoc = new DatagramSocket(ClinetPortNumber);
        String Command = "GET";

        byte Sendbuff[] = new byte[1024];
        Sendbuff = Command.getBytes();

        InetAddress ServerHost = InetAddress.getLocalHost();
        ClientSoc.send(new DatagramPacket(Sendbuff, Sendbuff.length, ServerHost, 5217));

        byte Receivebuff[] = new byte[1024];
        DatagramPacket dp = new DatagramPacket(Receivebuff, Receivebuff.length);
        ClientSoc.receive(dp);

        NewsMsg = new String(dp.getData(), 0, dp.getLength());
        System.out.println(NewsMsg);
        lblNewsHeadline.setText(NewsMsg);

        Thread.sleep(5000);
        ClientSoc.close();
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }
コード例 #14
0
ファイル: MailboxScout.java プロジェクト: syminical/C.A.L.M.
  public void run() {

    while (true) {

      DatagramPacket msg = new DatagramPacket(new byte[1000], 1000);

      try {

        socket.receive(msg);

      } catch (IOException e) {

      }
      ;

      String container = new String(msg.getData());

      container = container.trim();

      if (container.substring(0, container.indexOf(' ')).equals("vfd"))
        CALM.box.mailAction(container.substring(container.indexOf(' ') + 1, container.length()));
      else if (container.substring(0, container.indexOf(' ')).equals("dfv"))
        CALM.box.mailAction2(container.substring(container.indexOf(' ') + 1, container.length()));
    }
  }
コード例 #15
0
  private String receiveDataUdp(InetSocketAddress clientAddress) throws IOException, JSONException {
    EmployeeList employees = new EmployeeList();
    DatagramSocket datagramServer = new DatagramSocket(clientAddress);
    byte dataFromServer[] = new byte[2048];
    boolean isTimeExpired = false;
    datagramServer.setSoTimeout((int) SECONDS.toMillis(PROTOCOL_GROUP_TIMEOUT - 5));

    System.out.println(
        "[INFO] -----------------------------------------\n"
            + "[INFO] Collecting information from nodes....");
    while (!isTimeExpired) {
      DatagramPacket datagramPacketacket =
          new DatagramPacket(dataFromServer, dataFromServer.length);
      try {
        datagramServer.receive(datagramPacketacket);
      } catch (SocketTimeoutException e) {
        System.out.println(
            "[WARNING] -----------------------------------------\n"
                + "[WARNING] Waiting time expired...");
        isTimeExpired = true;
        continue;
      }
      String receivedJson = (String) deserialize(datagramPacketacket.getData());
      System.out.println("[INFO] " + "Received employee in JSON: " + receivedJson);
      employees.add(jsonToEmployee(receivedJson));
    }
    datagramServer.close();
    return employeeToXml(employees);
  }
コード例 #16
0
ファイル: UDPclient.java プロジェクト: joelsantiago/Java
  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);
    }
  }
コード例 #17
0
  /**
   * Initializes a new <tt>DatagramPacket</tt> instance which is a clone of a specific
   * <tt>DatagramPacket</tt> i.e. the properties of the clone <tt>DatagramPacket</tt> are clones of
   * the specified <tt>DatagramPacket</tt>.
   *
   * @param p the <tt>DatagramPacket</tt> to clone
   * @return a new <tt>DatagramPacket</tt> instance which is a clone of the specified
   *     <tt>DatagramPacket</tt>
   */
  public static DatagramPacket clone(DatagramPacket p) {
    synchronized (p) {
      byte[] pData = p.getData();
      byte[] cData = (pData == null) ? null : pData.clone();

      return new DatagramPacket(cData, p.getOffset(), p.getLength(), p.getAddress(), p.getPort());
    }
  }
コード例 #18
0
  @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");
  }
コード例 #19
0
  private String lookupFarm() {
    if (Response != null) {

      if (Response.isStillValid()) {

        return Response.getFarmID();
      }

      Response = null;
    }

    try {
      InetAddress CDPServer;
      DatagramSocket Socket;
      CDPQuery Query;
      byte[] Buffer;
      DatagramPacket Packet;

      /* Get the IP address of the CDP servers. */
      CDPServer = InetAddress.getByName(CDPServerName);

      /* Create a UDP socket for the CDP query. */
      Socket = new DatagramSocket();
      Socket.setSoTimeout(CDPTimeout);

      /* Build the CDP query. */
      Query = new CDPQuery(Constants.AZUREUS_NAME + " " + Constants.AZUREUS_VERSION);
      Buffer = Query.getBytes();
      Packet = new DatagramPacket(Buffer, Buffer.length, CDPServer, CDPPort);

      /* Send the query to the CDP server. */
      Socket.send(Packet);

      /* Receive the CDP response. */
      Buffer = new byte[CDPResponse.MaxSize];
      Packet.setData(Buffer);
      Socket.receive(Packet);
      if (Packet.getAddress() != CDPServer || Packet.getPort() != CDPPort)
        throw (new Exception("CDP server address mismatch on response"));

      /* Parse the CDP response. */
      Response = new CDPResponse(Packet.getData());

      /* Return the farmID from the CDP response. */
      return Response.getFarmID();
    } catch (Throwable Excpt) {

      if (Excpt instanceof UnknownHostException) {

      } else {

        Excpt.printStackTrace();
      }

      return "default";
    }
  }
コード例 #20
0
 public static DatagramPacket makePacket(char c1[], InetAddress inetAddress) {
   // byte[] sendMsg=(c1).toString().getBytes();
   String s1 = new String(c1);
   System.out.println(c1);
   byte[] sendMsg = s1.getBytes();
   DatagramPacket packet =
       new DatagramPacket(sendMsg, sendMsg.length, inetAddress, client.PORT_NUMBER_CLIENT);
   System.out.println(new String(packet.getData()));
   return packet;
 }
コード例 #21
0
  public void respond(DatagramPacket packet) {

    byte[] data = new byte[packet.getLength()];
    System.arraycopy(packet.getData(), 0, data, 0, packet.getLength());
    try {
      String s = new String(data, "8859_1");
      System.out.println(packet.getAddress() + " at port " + packet.getPort() + " says " + s);
    } catch (java.io.UnsupportedEncodingException ex) {
      // This shouldn't happen
    }
  }
コード例 #22
0
ファイル: Dreceiver.java プロジェクト: tomo0111/Java-program
  public static void main(String args[]) throws Exception {
    DatagramSocket ds = new DatagramSocket(3000);
    byte[] buf = new byte[1024];

    DatagramPacket dp = new DatagramPacket(buf, 1024);
    ds.receive(dp);

    String str = new String(dp.getData(), 0, dp.getLength());
    System.out.println(str);
    ds.close();
  }
コード例 #23
0
 private void listenToServer() throws IOException {
   do {
     Arrays.fill(rcvPacket.getData(), (byte) 0);
     requestSocket.receive(rcvPacket);
     message = new String(rcvPacket.getData());
     System.out.println("server>" + message);
     if (PACMANWINS.equals(message)) {
       board.gameState = 1;
     } else if (GHOSTWINS.equals(message)) {
       board.gameState = 2;
     } else {
       // create new thread so that we keep listening to server as
       // board is being updated
       new Thread() {
         public void run() {
           board.changeClientsState(message);
         }
       }.start();
     }
   } while (board.gameState == 0);
 }
コード例 #24
0
    SNMP_Parser(DatagramPacket dp) {
      data = new byte[dp.getLength()];

      int i;

      for (i = 0; i < dp.getLength(); i++) {
        data[i] = dp.getData()[i];
      }

      pointer = 0;
      data_remaining = data.length;
    }
コード例 #25
0
 public static void main(String[] args) throws Exception {
   InetAddress addr = InetAddress.getByName("230.0.0.1");
   MulticastSocket soc = new MulticastSocket(2056);
   soc.joinGroup(addr);
   DatagramPacket dp = new DatagramPacket(new byte[80], 80);
   for (int i = 0; i < 5; i++) {
     soc.receive(dp);
     String msg = new String(dp.getData(), 0, dp.getLength());
     System.out.println(msg);
   }
   soc.leaveGroup(addr);
   soc.close();
 }
コード例 #26
0
ファイル: DaytimeUDPClient.java プロジェクト: Bonu/Networking
 public static void main(String[] args) {
   try (DatagramSocket socket = new DatagramSocket(0)) {
     socket.setSoTimeout(10000);
     InetAddress host = InetAddress.getByName(HOSTNAME);
     DatagramPacket request = new DatagramPacket(new byte[1], 1, host, PORT);
     DatagramPacket response = new DatagramPacket(new byte[1024], 1024);
     socket.send(request);
     socket.receive(response);
     String result = new String(response.getData(), 0, response.getLength(), "US-ASCII");
     System.out.println(result);
   } catch (IOException ex) {
     ex.printStackTrace();
   }
 }
コード例 #27
0
 private void doRecv(DatagramPacket pack, int flags) throws IOException {
   IoBridge.recvfrom(
       false,
       fd,
       pack.getData(),
       pack.getOffset(),
       pack.getLength(),
       flags,
       pack,
       isNativeConnected);
   if (isNativeConnected) {
     updatePacketRecvAddress(pack);
   }
 }
コード例 #28
0
 public void run() {
   byte buffer[] = new byte[1024];
   DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
   String s;
   boolean done = false;
   try {
     while (!done) {
       ds.receive(dp);
       s = new String(dp.getData(), 0, dp.getLength());
       System.out.println("RCD MSG:" + s);
       if (s == "-") done = true;
     }
   } catch (IOException e) {
   }
 }
コード例 #29
0
  /**
   * Creates a new <tt>RawPacket</tt> from a specific <tt>DatagramPacket</tt> in order to have this
   * instance receive its packet data through its {@link #read(byte[], int, int)} method. Returns an
   * array of <tt>RawPacket</tt> with the created packet as its first element (and <tt>null</tt> for
   * the other elements).
   *
   * <p>Allows extenders to intercept the packet data and possibly filter and/or modify it.
   *
   * @param datagramPacket the <tt>DatagramPacket</tt> containing the packet data
   * @return an array of <tt>RawPacket</tt> containing the <tt>RawPacket</tt> which contains the
   *     packet data of the specified <tt>DatagramPacket</tt> as its first element.
   */
  protected RawPacket[] createRawPacket(DatagramPacket datagramPacket) {
    RawPacket[] pkts = rawPacketArrayPool.poll();
    if (pkts == null) pkts = new RawPacket[1];

    RawPacket pkt = rawPacketPool.poll();
    if (pkt == null) pkt = new RawPacket();

    pkt.setBuffer(datagramPacket.getData());
    pkt.setFlags(0);
    pkt.setLength(datagramPacket.getLength());
    pkt.setOffset(datagramPacket.getOffset());

    pkts[0] = pkt;
    return pkts;
  }
コード例 #30
0
ファイル: Server.java プロジェクト: brankeye/3303_A1
 private void readSendPacket(DatagramPacket sendPacket) {
   // print log
   System.out.println("Server: sending a packet...");
   System.out.println("To host: " + sendPacket.getAddress());
   System.out.println("Destination host port: " + sendPacket.getPort());
   Request req = new Request(sendPacket.getData(), sendPacket.getLength());
   String reqString = req.getString();
   byte reqBytes[] = req.getByteArray();
   System.out.print("String: '" + reqString + "'\n");
   System.out.print("Bytes:  '");
   int i = 0;
   while (i < req.getLength()) {
     System.out.print(reqBytes[i++]);
   }
   System.out.print("'\n");
 }