예제 #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
파일: 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();
  }
 /**
  * method to support proxy connection with server with udp connection
  *
  * @param serverIp
  * @param proxyport
  * @param serverport
  * @throws IOException
  */
 @SuppressWarnings("resource")
 public void proxyUDP(String serverIp, int proxyport, int serverport) throws IOException {
   DatagramSocket receiveSockets = new DatagramSocket(proxyport);
   while (true) {
     long milliSeconds;
     String modsentence = null;
     byte[] receivebuffer = new byte[1024];
     byte[] buffer = new byte[1024];
     DatagramPacket receivePacket = new DatagramPacket(receivebuffer, receivebuffer.length);
     receiveSockets.receive(receivePacket);
     milliSeconds = System.currentTimeMillis();
     InetAddress inet1 = receivePacket.getAddress();
     int port1 = receivePacket.getPort();
     modsentence = new String(receivePacket.getData()).trim();
     // if the connection type from proxy is not mentioned then use the
     // same client connection type
     if (this.tcpproxy == false && this.udpproxy == false) {
       if (modsentence.charAt(1) == 't') this.tcpproxy = true;
       else if (modsentence.charAt(1) == 'u') this.udpproxy = true;
     }
     // tcp connection to server for -t in command line
     if (this.tcpproxy == true) {
       Socket socket = new Socket(serverIp, this.portAddressTCPS);
       OutputStream os = socket.getOutputStream();
       DataOutputStream dos = new DataOutputStream(os);
       InputStream is = socket.getInputStream();
       InputStreamReader isr = new InputStreamReader(is);
       BufferedReader br = new BufferedReader(isr);
       dos.writeBytes(modsentence + "\n");
       dos.flush();
       modsentence = br.readLine();
     }
     // udp connection to server for -u in command line
     else if (this.udpproxy == true) {
       DatagramSocket sockets = new DatagramSocket();
       buffer = modsentence.getBytes();
       InetAddress inet = InetAddress.getByName(serverIp);
       DatagramPacket sendPacket =
           new DatagramPacket(buffer, buffer.length, inet, this.portAddressUDPS);
       sockets.send(sendPacket);
       sockets.receive(receivePacket);
       modsentence = new String(receivePacket.getData()).trim();
     }
     // append the RTT time from proxy to server
     modsentence = modsentence + "$$$spliter$$$";
     modsentence = modsentence + serverIP + "\t" + (System.currentTimeMillis() - milliSeconds);
     buffer = modsentence.getBytes();
     DatagramPacket sendPacket1 = new DatagramPacket(buffer, buffer.length, inet1, port1);
     receiveSockets.send(sendPacket1);
   }
 }
  public void run() {
    while (true) {
      try {
        // System.out.println("Waiting for client on port " +serverSocket.getLocalPort() + "...");
        byte[] receiveBuffer = new byte[512];
        DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
        UDPserverSocket.receive(receivePacket);
        System.out.println(
            "Request received from "
                + receivePacket.getSocketAddress()
                + ":"
                + receivePacket.getPort());

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

      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }
예제 #5
0
 @Override
 public void run() {
   /* Legacy UDP location manager daemon.
    */
   DatagramPacket packet;
   while (!Thread.currentThread().isInterrupted()) {
     try {
       packet = new DatagramPacket(new byte[1024], 1024);
       socket.receive(packet);
     } catch (SocketException e) {
       if (!Thread.currentThread().isInterrupted()) {
         LOGGER.warn("Exception in Server receive loop (exiting)", e);
       }
       break;
     } catch (Exception ie) {
       LOGGER.warn("Exception in Server receive loop (exiting)", ie);
       break;
     }
     try {
       process(packet);
       socket.send(packet);
     } catch (Exception se) {
       LOGGER.warn("Exception in send ", se);
     }
   }
   socket.close();
 }
예제 #6
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();
      }
    }
  }
예제 #7
0
    public void run() {

      while (!isThreadRunning) {

        byte[] ack_byte = new byte[2];

        DatagramPacket packet_ack = new DatagramPacket(ack_byte, ack_byte.length);
        try {
          socketAck.setSoTimeout(5);
        } catch (SocketException e) {
          e.printStackTrace();
        }
        try {
          socketAck.receive(packet_ack);
        } catch (IOException e) {
          e.printStackTrace();
        }
        byte[] ackData = packet_ack.getData();
        int packet_ack_num = getAckPaket(ackData);
        num_acked = Math.max(num_acked, packet_ack_num);
        Thread.yield();
      }

      socketAck.close();
    }
예제 #8
0
  public void processPackets() throws IOException {
    byte[] _receiveData = new byte[UDP_PACKET_BUFFER_SIZE];
    while (true) {
      DatagramPacket receivePacket = new DatagramPacket(_receiveData, _receiveData.length);
      serverSocket.receive(receivePacket);
      String data = new String(receivePacket.getData());
      System.out.println(data);
      ObjectMapper mapper = new ObjectMapper();
      JsonNode reqJSON = mapper.readValue(data, JsonNode.class);

      String action = reqJSON.get("action").getTextValue();
      if ("MOUSE_CLICK".equals(action)) {
        mc.leftClick();
      } else if ("ACCELEROMETER".equals(action)) {

      } else if ("MOUSE_MOVE".equals(action)) {
        JsonNode value = reqJSON.get("value");
        System.out.println(value);
        mc.scaleAndMove(value);
      }
      System.out.println("RECEIVED: " + data);
      for (int i = 0; i < UDP_PACKET_BUFFER_SIZE; i++) {
        _receiveData[i] = (byte) (0);
      }
    }
  }
예제 #9
0
  private void getAndSendInitialInfo() {
    byte[] idBuf = new byte[4];
    ByteBuffer buf = ByteBuffer.wrap(idBuf);
    buf.putInt(userid);
    DatagramPacket idPacket = new DatagramPacket(idBuf, idBuf.length);

    byte[] serverAckBuf = new byte[1];
    DatagramPacket serverAckPacket = new DatagramPacket(serverAckBuf, serverAckBuf.length);
    boolean receivedAck = false;
    while (!receivedAck) {
      try {
        ds.setSoTimeout(REG_TIMEOUT);
        System.out.println("CLIENT " + userid + ": attempting to register");
        ds.send(idPacket);
        ds.receive(serverAckPacket);
        receivedAck = true;
        byte indicator = serverAckBuf[0];
        System.out.println("CLIENT " + userid + ": received ack: " + indicator);
        if (indicator == 0 || indicator == 1) {
          team = indicator;
        } else {
          // server error, must exit
          throw new RuntimeException(
              "Server responded with code: " + indicator + ", will not start.");
        }
      } catch (SocketTimeoutException e) {
        continue;
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    System.out.println("CLIENT:" + userid + " Done registering.");
    // throw new UnsupportedOperationException();
  }
예제 #10
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;
  }
예제 #11
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());
     }
   }
 }
 public void receiveMessage(byte[] buffer) throws Exception {
   DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
   synchronized (m_Socket) {
     m_Socket.setSoTimeout(m_Timeout);
     m_Socket.receive(packet);
   }
 }
예제 #13
0
    public void run() {
      while (_datagramSocket != null && _datagramSocket == _socket && !_datagramSocket.isClosed()) {
        try {
          DatagramPacket packet = new DatagramPacket(new byte[MAX_PACKET_SIZE], MAX_PACKET_SIZE);
          _datagramSocket.receive(packet);
          DnsMessage answer = new DnsMessage();
          answer.decode(ByteBuffer.wrap(packet.getData()));
          MsgContainer msgContainer;

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

          if (msgContainer != null) {
            synchronized (msgContainer.getQuery()) {
              msgContainer.setAnswer(answer);
              msgContainer.getQuery().notify();
            }
          } else LOG.warn("Drop DNS Answser {}, as can not found a query with same ID", answer);
        } catch (IOException e) {
          close();
        }
      }
      close();
      LOG.debug("DNS acceptor done");
    }
예제 #14
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();
  }
예제 #15
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;
  }
  @Override
  protected void run() throws Exception {
    while (isRunning()) {

      // PACKET RECEIVED

      socket.receive(packet);
      int length = packet.getLength();
      byte[] data = ByteBuffer.allocate(length).put(packet.getData(), 0, length).array();
      SocketAddress address = packet.getSocketAddress();

      // ALLOCATE CLIENT
      SWGClient client =
          (!connections.containsKey(address))
              ? clientFactory.create(address)
              : connections.get(address);

      data = packagingService.disassemble(data, client.getCrc());

      if (data.length == 1) {
        // TODO: Queue logout packet
        // TODO:  Disconnect client
      } else if (data.length == 0) {

      } else {

        // TODO: Create SWG Message from data

      }
    }
  }
예제 #17
0
  public void run() {
    printWelcome();
    while (!welcomingSocket.isClosed()) {
      while (!canCreateNewWorker()) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          continue;
        }
      }

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

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

        ConnectionHandler conn = new ConnectionHandler(strategy, reqPkt, plp, pep, rngSeed, maxN);
        Thread connectionHandler = new Thread(conn);
        connectionHandler.start();
        workers.add(new Worker(connectionHandler, conn, System.currentTimeMillis()));
      } catch (IOException e) {
        continue;
      }
    }
  }
예제 #18
0
 /** Accept incoming events and processes them. */
 @Override
 public void run() {
   while (isActive()) {
     if (datagramSocket.isClosed()) {
       // OK we're done.
       return;
     }
     try {
       final byte[] buf = new byte[maxBufferSize];
       final DatagramPacket packet = new DatagramPacket(buf, buf.length);
       datagramSocket.receive(packet);
       final ByteArrayInputStream bais =
           new ByteArrayInputStream(packet.getData(), packet.getOffset(), packet.getLength());
       logEventInput.logEvents(logEventInput.wrapStream(bais), this);
     } catch (final OptionalDataException e) {
       if (datagramSocket.isClosed()) {
         // OK we're done.
         return;
       }
       logger.error("OptionalDataException eof=" + e.eof + " length=" + e.length, e);
     } catch (final EOFException e) {
       if (datagramSocket.isClosed()) {
         // OK we're done.
         return;
       }
       logger.info("EOF encountered");
     } catch (final IOException e) {
       if (datagramSocket.isClosed()) {
         // OK we're done.
         return;
       }
       logger.error("Exception encountered on accept. Ignoring. Stack Trace :", e);
     }
   }
 }
  public static void main(String[] args) throws Exception {
    if (args.length != 2) {
      System.err.println("Usage: java RFS862_UdpClient <destination host> <destination port>");
      System.exit(1);
    }
    // get the dest host + port from console
    String dest_host = args[0];
    int dest_port = Integer.parseInt(args[1]);

    // input stream from the console
    BufferedReader inFromUserConsole = new BufferedReader(new InputStreamReader(System.in));
    // new udp socket
    DatagramSocket clientSocket = new DatagramSocket();
    InetAddress IPAddress = InetAddress.getByName(dest_host);
    // sizes of sent and received data
    byte[] sendData = new byte[1024];
    byte[] receiveData = new byte[1024];
    // the message from the client
    System.out.println("Please input a message:");
    String sentence = inFromUserConsole.readLine();

    sendData = sentence.getBytes();
    // build the datagram package
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, dest_port);
    // send it to the server
    clientSocket.send(sendPacket);
    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
    // get data from the server
    clientSocket.receive(receivePacket);
    // cast the received message as string
    String modifiedSentence = new String(receivePacket.getData());
    System.out.println(modifiedSentence);
    // close the client socket
    clientSocket.close();
  }
예제 #20
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);
      }
    }
  }
예제 #21
0
  /**
   * Sends a Radius packet to the server and awaits an answer.
   *
   * @param request packet to be sent
   * @param port server port number
   * @return response Radius packet
   * @exception RadiusException malformed packet
   * @exception IOException communication error (after getRetryCount() retries)
   */
  public RadiusPacket communicate(RadiusPacket request, int port)
      throws IOException, RadiusException {
    DatagramPacket packetIn =
        new DatagramPacket(
            new byte[RadiusPacket.MAX_PACKET_LENGTH], RadiusPacket.MAX_PACKET_LENGTH);
    DatagramPacket packetOut = makeDatagramPacket(request, port);

    DatagramSocket socket = getSocket();
    for (int i = 1; i <= getRetryCount(); i++) {
      try {
        socket.send(packetOut);
        socket.receive(packetIn);
        return makeRadiusPacket(packetIn, request);
      } catch (IOException ioex) {
        if (i == getRetryCount()) {
          if (logger.isErrorEnabled()) {
            if (ioex instanceof SocketTimeoutException)
              logger.error("communication failure (timeout), no more retries");
            else logger.error("communication failure, no more retries", ioex);
          }
          throw ioex;
        }
        if (logger.isInfoEnabled()) logger.info("communication failure, retry " + i);
        // TODO increase Acct-Delay-Time by getSocketTimeout()/1000
        // this changes the packet authenticator and requires packetOut to be
        // calculated again (call makeDatagramPacket)
      }
    }

    return null;
  }
예제 #22
0
파일: UDPClient.java 프로젝트: magnlun/cnt
  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));
    }
  }
예제 #23
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;
        }
      }
    }
예제 #24
0
파일: Arcon.java 프로젝트: prinsessa/Arcon
  public boolean canConnect() {

    byte[] buf = new byte[PACKETSIZE];
    DatagramPacket packet = new DatagramPacket(buf, buf.length);

    try {
      sendCommand("status");
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }

    try {
      socket.receive(packet);
    } catch (IOException e) {
      e.printStackTrace();
      return false;
    }

    String received = "";
    try {
      // must be set explicitly to "ISO-8859-1" or we'll run into problems
      // sending or receiving...
      received = new String(packet.getData(), "ISO-8859-1");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    if (received.startsWith(PREFIX_PRINT)) {
      return true;
    }
    return false;
  }
예제 #25
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();
  }
예제 #26
0
  /** @invisible */
  public void run() {
    if (_myDatagramSocket != null) {
      if (isRunning) {
        Logger.printProcess("UdpServer.run()", "UdpServer is running @ " + _myPort);
      }
    } else {
      Logger.printError("UdpServer.run()", "Socket is null. closing UdpServer.");
      return;
    }

    while (isRunning) {
      try {
        byte[] myBuffer = new byte[_myDatagramSize];
        DatagramPacket myPacket = new DatagramPacket(myBuffer, _myDatagramSize);
        _myDatagramSocket.receive(myPacket);
        _myListener.process(myPacket, _myPort);
      } catch (IOException ioex) {
        Logger.printProcess("UdpServer.run()", " socket closed.");
        break;
      } catch (ArrayIndexOutOfBoundsException ex) {
        Logger.printError("UdpServer.run()", "ArrayIndexOutOfBoundsException:  " + ex);
      }
    }
    dispose();
  }
예제 #27
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();
      }
    }
  }
  @Override
  public void run() {
    try {
      socket = new DatagramSocket(port);

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

        byte[] buf = new byte[256];

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

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

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

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
예제 #29
0
  public PingResult ping(ScanningSubject subject, int count) throws IOException {
    PingResult result = new PingResult(subject.getAddress());

    DatagramSocket socket = sockets.bind(new DatagramSocket());
    socket.setSoTimeout(timeout);
    socket.connect(subject.getAddress(), PROBE_UDP_PORT);

    for (int i = 0; i < count && !Thread.currentThread().isInterrupted(); i++) {
      long startTime = System.currentTimeMillis();
      byte[] payload = new byte[8];
      ByteBuffer.wrap(payload).putLong(startTime);
      DatagramPacket packet = new DatagramPacket(payload, payload.length);
      try {
        socket.send(packet);
        socket.receive(packet);
      } catch (PortUnreachableException e) {
        result.addReply(System.currentTimeMillis() - startTime);
      } catch (SocketTimeoutException ignore) {
      } catch (NoRouteToHostException e) {
        // this means that the host is down
        break;
      } catch (SocketException e) {
        if (e.getMessage().contains(/*No*/ "route to host")) {
          // sometimes 'No route to host' also gets here...
          break;
        }
      } catch (IOException e) {
        LOG.log(FINER, subject.toString(), e);
      }
    }
    return result;
  }
예제 #30
0
파일: Server.java 프로젝트: pauljs/CS283
  // start up the server
  public void start() {
    DatagramSocket socket = null;
    try {
      // create a datagram socket, bind to port port. See
      // http://docs.oracle.com/javase/tutorial/networking/datagrams/ for
      // details.

      socket = new DatagramSocket(port);

      // receive packets in an infinite loop
      while (true) {
        // create an empty UDP packet
        byte[] buf = new byte[Server.MAX_PACKET_SIZE];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        // call receive (this will poulate the packet with the received
        // data, and the other endpoint's info)
        socket.receive(packet);
        // start up a worker thread to process the packet (and pass it
        // the socket, too, in case the
        // worker thread wants to respond)
        WorkerThread t = new WorkerThread(packet, socket);
        t.start();
      }
    } catch (IOException e) {
      // we jump out here if there's an error, or if the worker thread (or
      // someone else) closed the socket
      e.printStackTrace();
    } finally {
      if (socket != null && !socket.isClosed()) socket.close();
    }
  }