Beispiel #1
1
  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();
  }
Beispiel #2
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 #3
0
  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();
  }
 public static void wait(DatagramSocket skt, DatagramPacket request)
     throws IOException, InterruptedException {
   // stop till you receive
   skt.receive(request);
   System.out.println("request received");
   Thread.sleep(2000);
 }
  public void run() {
    System.out.println("ExeUDPServer开始监听..." + UDP_PORT);
    DatagramSocket ds = null;
    try {
      ds = new DatagramSocket(UDP_PORT);
    } catch (BindException e) {
      System.out.println("UDP端口使用中...请重关闭程序启服务器");
    } catch (SocketException e) {
      e.printStackTrace();
    }

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

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

      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  public 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();
  }
  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 #8
0
  public static void main(final String... args) throws Throwable {
    final String remotehost = args[0];
    final int remoteport = Integer.parseInt(args[1]);
    final DatagramSocket socket = new DatagramSocket();

    final byte buffer[] = new byte[512];

    final InetSocketAddress remote = new InetSocketAddress(remotehost, remoteport);

    buffer[0] = ENQUIRY;
    buffer[1] = END_OF_TRANSMISSION;
    socket.send(new DatagramPacket(buffer, 2, remote));

    final DatagramPacket p = new DatagramPacket(buffer, buffer.length);
    socket.receive(p);

    if ((p.getLength() == 2) && (buffer[0] == ACKNOWLEDGE) && (buffer[1] == END_OF_TRANSMISSION))
      System.out.println("Connection established");
    else {
      System.out.println("Connection failed");
      return;
    }

    for (; ; ) {
      int ptr = 0;
      for (int d; (d = System.in.read()) != '\n'; ) buffer[ptr++] = (byte) d;

      socket.send(new DatagramPacket(buffer, ptr, remote));
    }
  }
 public static void main(String args[]) {
   DatagramSocket aSocket = null;
   try {
     aSocket = new DatagramSocket();
     String stringMsg = "0";
     String prevReply = "0";
     InetAddress aHost =
         InetAddress.getByName("localhost"); // recieve a message from the same computer
     int serverPort = 6789; // agreed port
     while (true) {
       stringMsg = "" + (Integer.parseInt(stringMsg) + 1);
       byte[] message = stringMsg.getBytes();
       DatagramPacket request = new DatagramPacket(message, message.length, aHost, serverPort);
       System.out.printf("Producer: Sending: %s\n", stringMsg);
       aSocket.send(request); // send a message
       byte[] buffer = new byte[1000];
       DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
       aSocket.receive(reply); // wait for a reply
       try {
         Thread.sleep(2000); // have a small waiting period
       } catch (InterruptedException e) {
       }
     }
   } catch (SocketException e) {
     System.out.println("Socket: " + e.getMessage());
   } catch (IOException e) {
     System.out.println("IO: " + e.getMessage());
   } finally {
     if (aSocket != null) aSocket.close();
   }
 }
  /**
   * 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
    }
  }
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) {
      }
    }
  }
  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);
        }
      }
    }
  }
Beispiel #13
0
  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()));
    }
  }
Beispiel #14
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);
    }
  }
  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();
  }
Beispiel #16
0
 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();
   }
 }
 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) {
   }
 }
Beispiel #18
0
  public static void main(String args[]) throws Exception {
    BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
    DatagramSocket clientSocket = new DatagramSocket();
    InetAddress IPAddress = InetAddress.getByName("62.38.242.7");
    byte[] sendData = new byte[1024];
    byte[] receiveData = new byte[1024];
    String sentence = inFromUser.readLine();
    sendData = sentence.getBytes();
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9310);
    clientSocket.send(sendPacket);

    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
    clientSocket.receive(receivePacket);
    String modifiedSentence = new String(receivePacket.getData());
    System.out.println("FROM SERVER:" + modifiedSentence);
    clientSocket.close();
  }
 /**
  * Main method keeps waiting for request and do math operation accordingly
  *
  * @param args
  */
 public static void main(String args[]) {
   DatagramSocket aSocket = null;
   try {
     aSocket = new DatagramSocket(6789);
     byte[] buffer = new byte[1000];
     while (true) {
       DatagramPacket request = new DatagramPacket(buffer, buffer.length);
       aSocket.receive(request);
       // receive byte array of equation and put it in string
       String equation = new String(request.getData());
       String answer = "";
       String[] split = equation.split(" ");
       // parse to integer and calculate
       String op = split[1];
       double var1 = Double.parseDouble(split[0]);
       double var2 = Double.parseDouble(split[2]);
       if (op.equals("+")) {
         answer = Double.toString(var1 + var2);
       } else if (op.equals("-")) {
         answer = Double.toString(var1 - var2);
       } else if (op.toLowerCase().equals("X") || op.toLowerCase().equals("x")) {
         answer = Double.toString(var1 * var2);
       } else if (op.equals("/")) {
         answer = Double.toString(var1 / var2);
       }
       // send answer back
       DatagramPacket reply =
           new DatagramPacket(
               answer.getBytes(),
               (answer.getBytes()).length,
               request.getAddress(),
               request.getPort());
       aSocket.send(reply);
     }
   } catch (SocketException e) {
     System.out.println("Socket: " + e.getMessage());
   } catch (IOException e) {
     System.out.println("IO: " + e.getMessage());
   } finally {
     if (aSocket != null) {
       aSocket.close();
     }
   }
 }
  private MyMessage getMessage() throws Exception {
    int dataRecieved = 0;
    String m = new String();
    String t;

    // FIXME needs to get multiple packets and messages
    // System.out.println("RT: Now waiting for message data");

    while (dataRecieved < totalDataSize) {
      // Get message data
      response = new byte[65000];
      DatagramPacket packet = new DatagramPacket(response, response.length);
      socket.receive(packet);
      Packet p = new Packet(packet.getData());
      // System.out.println("RT: Got message with seqnum: "+p.getSeqNum());

      // If we have a handshake packet something broke
      if (p.isHandshake()) {
        return null;
      }

      // If next in-order packet grab data and is not corrupt
      // XXX
      if (p.getSeqNum() == seqNum + 1 && p.checkChecksum()) {
        // Get the message ( part? )
        // System.out.println("RT: Is correct seqnum");
        t = p.getMessages().get(0).getMessageContents();
        // System.out.println("RT: Got message packet: " + t);
        m += t;

        // Send ack
        sendAck(p, packet);

        // Increment counters
        dataRecieved += t.length();
        seqNum++;
      } else {
        System.out.println("RT: Is NOT correct seqnum");
      }
    }
    MyMessage result = new MyMessage();
    result.setMessageContents(m);
    return result;
  }
Beispiel #21
0
 public void run() {
   byte[] buf = new byte[BUF_SIZE];
   DatagramPacket incomingData = new DatagramPacket(buf, buf.length);
   try {
     while (true) {
       sock.receive(incomingData);
       System.out.println(
           "UDP From:"
               + incomingData.getAddress().getHostAddress()
               + ":"
               + incomingData.getPort());
       System.out.println(new String(incomingData.getData(), 0, incomingData.getLength()));
       System.out.flush();
       incomingData.setLength(buf.length);
     }
   } catch (IOException io_ex) {
     io_ex.printStackTrace();
   }
 }
Beispiel #22
0
  // waits to receive packets
  private DatagramPacket receive() {
    byte data[] = new byte[100];
    DatagramPacket receivePacket = new DatagramPacket(data, data.length);
    System.out.println("Server: waiting for a packet...\n");

    // Block until a datagram packet is received from receiveSocket.
    try {
      receiveSocket.receive(receivePacket);
    } catch (IOException e) {
      System.out.print("IO Exception: likely:");
      System.out.println("Receive Socket Timed Out.\n" + e);
      e.printStackTrace();
      System.exit(1);
    }

    readReceivePacket(receivePacket);

    return receivePacket;
  }
  public static void main(String args[]) throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    DatagramSocket s = new DatagramSocket();
    InetAddress ip = InetAddress.getByName("localhost");
    byte[] send = new byte[1000];
    byte[] rec = new byte[1000];

    String ss = br.readLine();
    send = ss.getBytes();
    DatagramPacket sendpacket = new DatagramPacket(send, send.length, ip, 1200);
    s.send(sendpacket);

    DatagramPacket recpacket = new DatagramPacket(rec, rec.length);
    s.receive(recpacket);

    String sss = new String(recpacket.getData(), 0, recpacket.getLength());
    System.out.println(sss);
  }
  public static void main(String args[]) throws Exception {
    // Open socket loclahost:6000
    DatagramSocket serverSocket = new DatagramSocket(6000, InetAddress.getByName("localhost"));
    byte[] receiveData = new byte[1024];
    byte[] sendData = new byte[1024];

    // Hanging on
    while (true) {
      DatagramPacket readPacket = new DatagramPacket(receiveData, receiveData.length);
      serverSocket.receive(readPacket);
      String readData = new String(readPacket.getData());
      System.out.println("UDP Server, " + readData);
      InetAddress ip = readPacket.getAddress();
      int port = readPacket.getPort();
      String output = "Hello, " + readData;
      sendData = output.getBytes();
      DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ip, port);
      serverSocket.send(sendPacket);
    }
  }
Beispiel #25
0
 static byte[] sendReq(byte abyte0[], int i, String s, int j) throws Exception {
   DatagramSocket datagramsocket = new DatagramSocket(i);
   try {
     datagramsocket.setSoTimeout(30000);
     datagramsocket.send(new DatagramPacket(abyte0, abyte0.length, InetAddress.getByName(s), j));
     byte abyte1[] = new byte[512];
     DatagramPacket datagrampacket = new DatagramPacket(abyte1, abyte1.length);
     datagramsocket.receive(datagrampacket);
     byte abyte2[] = new byte[datagrampacket.getLength()];
     System.arraycopy(datagrampacket.getData(), 0, abyte2, 0, datagrampacket.getLength());
     datagramsocket.close();
     return abyte2;
   } catch (Exception exception) {
     try {
       datagramsocket.close();
     } catch (Exception exception1) {
     }
     throw exception;
   }
 }
  public void runClient() throws IOException {
    try {
      dataClient = new DatagramSocket();

      dataOut = "1".getBytes();
      dataSent = new DatagramPacket(dataOut, dataOut.length, getAddress(), getPort());
      dataClient.send(dataSent);

      Scanner input = new Scanner(System.in);
      // setSocket(new Socket(getAddress(),getPort()));
      // in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      // out = new PrintWriter(socket.getOutputStream(),true);
      while (true) {
        /* Preparing Input from Server */
        // serverResponse = in.readLine();
        try {
          dataReceived.setData(dataIn);
          dataClient.receive(dataReceived);
          serverResponse = new String(dataReceived.getData());

          if (serverResponse.equals("1")) { // if key for getting client input is called
            /* Outputting to Server */
            clientResponse = input.nextLine(); // Get what the user types.

            dataOut = clientResponse.getBytes();
            dataSent = new DatagramPacket(dataOut, dataOut.length, getAddress(), getPort());
            dataClient.send(dataSent);
            // out.println(clientResponse);
          } else {
            System.out.println(serverResponse);
          }
        } catch (Exception e) {
        }
      }

    } catch (Exception e) {
      /**/
    } finally {
      /* socket.close(); */
    }
  }
Beispiel #27
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);
 }
 public static void main(String[] args) {
   if (args.length != 1) System.out.println("This program requires a command line argument.");
   else {
     int port = Integer.parseInt(args[0]);
     final int MAX_LEN = 10;
     // This is the assumed maximum byte length of the datagram to be received.
     try {
       DatagramSocket mySocket = new DatagramSocket(port);
       // instantiates a datagram socket for receiving the data
       byte[] buffer = new byte[MAX_LEN];
       DatagramPacket datagram = new DatagramPacket(buffer, MAX_LEN);
       mySocket.receive(datagram);
       String message = new String(buffer);
       System.out.println(message);
       mySocket.close();
     } // end try
     catch (Exception ex) {
       ex.printStackTrace();
     }
   } // end else
 } // end main
Beispiel #29
0
  public void run() {

    System.out.println("               -----------------UDP Demo Server-----------------" + "\n\n");

    while (true) {
      try {
        // Create a new socket connection bound to the defined port
        DatagramSocket sock = new DatagramSocket(BROADCAST_PORT);

        System.out.println("Waiting for data on local port: " + sock.getLocalPort());

        // Create a packet to contain incoming data
        byte[] buf = new byte[256];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);

        // Wait for incoming data (receive() is a blocking method)
        sock.receive(packet);

        // Retrieve data from packet and display
        String data = new String(packet.getData());
        int endIndex = data.indexOf(0);
        data = data.substring(0, endIndex);
        int remotePort = packet.getPort();
        System.out.println("Received data from remote port " + remotePort + ":\n" + data);

        // Determine origin of packet and display information
        InetAddress remoteAddress = packet.getAddress();
        System.out.println("Sent from address: " + remoteAddress.getHostAddress());

        // Send back an acknowledgment
        String ack = "RECEIVED " + new Date().toString();
        sock.send(new DatagramPacket(ack.getBytes(), ack.length(), remoteAddress, remotePort));

        sock.close();
      } catch (IOException ioe) {
        System.out.println("Error: IOException - " + ioe.toString());
      }
    }
  }
Beispiel #30
0
 static int Challenge(DatagramSocket datagramsocket, InetAddress inetaddress, int i)
     throws Exception {
   System.out.print("Sending the challenge request...");
   byte abyte0[] = Cmd_Challenge();
   datagramsocket.send(new DatagramPacket(abyte0, abyte0.length, inetaddress, i));
   try {
     Thread.sleep(50L);
   } catch (Exception exception) {
   }
   abyte0 = new byte[256];
   DatagramPacket datagrampacket = new DatagramPacket(abyte0, abyte0.length);
   datagramsocket.receive(datagrampacket);
   ReqAccept reqaccept = new ReqAccept(abyte0);
   if (!((Req) (reqaccept)).legal) {
     System.out.println("Connection rejected");
     Print(datagrampacket);
     throw new Exception();
   } else {
     System.out.println(" ok");
     return reqaccept.Id;
   }
 }