List of usage examples for java.net DatagramSocket receive
public synchronized void receive(DatagramPacket p) throws IOException
From source file:org.apache.camel.component.mina.MinaUdpWithInOutUsingPlainSocketTest.java
private String sendAndReceiveUdpMessages(String input) throws Exception { DatagramSocket socket = new DatagramSocket(); InetAddress address = InetAddress.getByName("127.0.0.1"); byte[] data = input.getBytes(); DatagramPacket packet = new DatagramPacket(data, data.length, address, PORT); LOG.debug("+++ Sending data +++"); socket.send(packet);//w ww . j ava 2 s.c o m Thread.sleep(1000); byte[] buf = new byte[128]; DatagramPacket receive = new DatagramPacket(buf, buf.length, address, PORT); LOG.debug("+++ Receving data +++"); socket.receive(receive); socket.close(); return new String(receive.getData(), 0, receive.getLength()); }
From source file:com.esri.geoevent.test.performance.ClockSync.java
@Override public void run() { DatagramSocket socket = null; try {//from ww w . ja va2s . c o m byte[] incomingBuffer = new byte[1024]; DatagramPacket packet = new DatagramPacket(incomingBuffer, incomingBuffer.length); ByteBuffer bb = ByteBuffer.allocate(8); DatagramPacket outgoingPacket = new DatagramPacket(bb.array(), 0, 8, null, port); socket = new DatagramSocket(port); socket.setSoTimeout(100); while (isRunning.get()) { try { socket.receive(packet); long now = System.currentTimeMillis(); bb.putLong(now); outgoingPacket.setAddress(packet.getAddress()); outgoingPacket.setPort(packet.getPort()); socket.send(outgoingPacket); bb.clear(); //System.out.println("Sent the time " + now); } catch (SocketTimeoutException ex) { // Do nothing if nothing was sent. } } } catch (BindException e) { // port is in use - increment and try again port++; this.run(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(socket); } }
From source file:org.apache.jmeter.JMeter.java
private static void waitForSignals(final List<JMeterEngine> engines, DatagramSocket socket) { byte[] buf = new byte[80]; System.out.println(/*ww w.j a v a 2 s . co m*/ "Waiting for possible Shutdown/StopTestNow/Heapdump message on port " + socket.getLocalPort()); DatagramPacket request = new DatagramPacket(buf, buf.length); try { while (true) { socket.receive(request); InetAddress address = request.getAddress(); // Only accept commands from the local host if (address.isLoopbackAddress()) { String command = new String(request.getData(), request.getOffset(), request.getLength(), "ASCII"); System.out.println("Command: " + command + " received from " + address); log.info("Command: " + command + " received from " + address); if (command.equals("StopTestNow")) { for (JMeterEngine engine : engines) { engine.stopTest(true); } } else if (command.equals("Shutdown")) { for (JMeterEngine engine : engines) { engine.stopTest(false); } } else if (command.equals("HeapDump")) { HeapDumper.dumpHeap(); } else { System.out.println("Command: " + command + " not recognised "); } } } } catch (Exception e) { System.out.println(e); } finally { socket.close(); } }
From source file:org.apache.camel.component.netty.NettyUdpWithInOutUsingPlainSocketTest.java
private String sendAndReceiveUdpMessages(String input) throws Exception { DatagramSocket socket = new DatagramSocket(); InetAddress address = InetAddress.getByName("127.0.0.1"); // must append delimiter byte[] data = (input + "\n").getBytes(); DatagramPacket packet = new DatagramPacket(data, data.length, address, PORT); LOG.debug("+++ Sending data +++"); socket.send(packet);/*from w ww .ja v a 2 s.co m*/ Thread.sleep(1000); byte[] buf = new byte[128]; DatagramPacket receive = new DatagramPacket(buf, buf.length, address, PORT); LOG.debug("+++ Receiving data +++"); socket.receive(receive); socket.close(); return new String(receive.getData(), 0, receive.getLength()); }
From source file:gravity.android.discovery.DiscoveryServer.java
public void run() { Log.v("DISCOVERY_SERVER", "SERVER STARTED"); DatagramSocket serverSocket = null; try {//from w w w . j a v a2 s . c o m serverSocket = new DatagramSocket(port); byte[] receiveData; byte[] sendData; while (this.isInterrupted() == false) { receiveData = new byte[128]; sendData = new byte[128]; try { Log.v("DISCOVERY_SERVER", "LISTENING"); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String sentence = new String(receivePacket.getData()); if (sentence != null) Log.v("DISCOVERY_SERVER", "RECEIVED: " + sentence.substring(0, receivePacket.getLength()).trim()); if (sentence != null && sentence.substring(0, receivePacket.getLength()).trim().equals(token)) { Log.v("DISCOVERY_SERVER", "SEND '" + nome + "' to " + receivePacket.getAddress().getHostAddress() + ":" + receivePacket.getPort()); JSONObject sendDataJson = new JSONObject(); sendDataJson.accumulate("name", nome); sendDataJson.accumulate("port_to_share", port_to_share); //sendData = (nome + "," + port_to_share).getBytes(); sendData = sendDataJson.toString().getBytes(); //Prakash: converts the data to json objects to avoid troubles DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort()); serverSocket.send(sendPacket); } } catch (Exception ex) { ex.printStackTrace(); Log.e("DISCOVERY_SERVER", ex.toString()); } } } catch (Exception e) { e.printStackTrace(); Log.e("DISCOVERY_SERVER", e.toString()); } finally { try { if (serverSocket != null) serverSocket.close(); } catch (Exception ex) { } } }
From source file:org.apache.axis2.transport.udp.UDPSender.java
private void waitForReply(MessageContext messageContext, DatagramSocket datagramSocket, String contentType) throws IOException { // piggy back message constant is used to pass a piggy back // message context in asnych model if (!(messageContext.getAxisOperation() instanceof OutInAxisOperation) && messageContext.getProperty(org.apache.axis2.Constants.PIGGYBACK_MESSAGE) == null) { return;//ww w. jav a2 s . c o m } byte[] inputBuffer = new byte[4096]; //TODO set the maximum size parameter DatagramPacket packet = new DatagramPacket(inputBuffer, inputBuffer.length); datagramSocket.receive(packet); // create the soap envelope try { MessageContext respMessageContext = messageContext.getOperationContext() .getMessageContext(WSDL2Constants.MESSAGE_LABEL_IN); InputStream inputStream = new ByteArrayInputStream(inputBuffer, 0, packet.getLength()); SOAPEnvelope envelope = TransportUtils.createSOAPMessage(respMessageContext, inputStream, contentType); respMessageContext.setEnvelope(envelope); } catch (XMLStreamException e) { throw new AxisFault("Can not build the soap message ", e); } }
From source file:org.starnub.starnubserver.servers.starbound.UDPProxyServer.java
public void run() { InetAddress IPAddress;/*from w w w .java 2s . co m*/ DatagramSocket ds; try { ds = new DatagramSocket(starnubPort); IPAddress = InetAddress.getByName(starboundAddress); } catch (SocketException | UnknownHostException e1) { StarNub.getLogger().cFatPrint("StarNub", ExceptionUtils.getMessage(e1)); e1.printStackTrace(); return; } byte[] request = new byte[1024]; byte[] reply = new byte[4096]; while (!stopping) { try { DatagramPacket from_client = new DatagramPacket(request, request.length); ds.receive(from_client); byte[] real_request = new byte[from_client.getLength()]; System.arraycopy(request, 0, real_request, 0, from_client.getLength()); DatagramPacket sendPacket = new DatagramPacket(real_request, real_request.length, IPAddress, starboundPort); ds.send(sendPacket); DatagramPacket from_server = new DatagramPacket(reply, reply.length); ds.receive(from_server); byte[] real_reply = new byte[from_server.getLength()]; System.arraycopy(reply, 0, real_reply, 0, from_server.getLength()); InetAddress address = from_client.getAddress(); int port = from_client.getPort(); DatagramPacket to_client = new DatagramPacket(real_reply, real_reply.length, address, port); ds.send(to_client); } catch (Exception e) { StarNub.getLogger().cFatPrint("StarNub", ExceptionUtils.getMessage(e)); return; } } }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Returns the network address with which the task manager shall announce itself to the job manager. To determine * the address this method exchanges packets with the job manager. * /*w w w . j a v a2 s . co m*/ * @param jobManagerAddress * the address of the job manager * @return the address with which the task manager shall announce itself to the job manager * @throws DiscoveryException * thrown if an error occurs during the packet exchange */ public static InetAddress getTaskManagerAddress(final InetAddress jobManagerAddress) throws DiscoveryException { final int magicNumber = GlobalConfiguration.getInteger(MAGICNUMBER_KEY, DEFAULT_MAGICNUMBER); final int discoveryPort = GlobalConfiguration.getInteger(DISCOVERYPORT_KEY, DEFAULT_DISCOVERYPORT); InetAddress taskManagerAddress = null; DatagramSocket socket = null; try { socket = new DatagramSocket(); LOG.debug("Setting socket timeout to " + CLIENTSOCKETTIMEOUT); socket.setSoTimeout(CLIENTSOCKETTIMEOUT); final DatagramPacket responsePacket = new DatagramPacket(new byte[RESPONSE_PACKET_SIZE], RESPONSE_PACKET_SIZE); for (int retries = 0; retries < DISCOVERFAILURERETRIES; retries++) { final DatagramPacket addressRequest = createTaskManagerAddressRequestPacket(magicNumber); addressRequest.setAddress(jobManagerAddress); addressRequest.setPort(discoveryPort); LOG.debug("Sending Task Manager address request to " + addressRequest.getSocketAddress()); socket.send(addressRequest); try { socket.receive(responsePacket); } catch (SocketTimeoutException ste) { LOG.warn("Timeout wainting for task manager address reply. Retrying..."); continue; } if (!isPacketForUs(responsePacket, magicNumber)) { LOG.warn("Received packet which is not destined to this Nephele setup"); continue; } final int packetTypeID = getPacketTypeID(responsePacket); if (packetTypeID != TM_ADDRESS_REPLY_ID) { LOG.warn("Received response of unknown type " + packetTypeID + ", discarding..."); continue; } taskManagerAddress = extractInetAddress(responsePacket); break; } } catch (IOException ioe) { throw new DiscoveryException(StringUtils.stringifyException(ioe)); } finally { if (socket != null) { socket.close(); } } if (taskManagerAddress == null) { throw new DiscoveryException("Unable to obtain task manager address"); } return taskManagerAddress; }
From source file:com.ionicsdk.discovery.Discovery.java
public void doIdentify(final JSONObject opts, final CallbackContext callbackContext) { new AsyncTask<Integer, Void, Void>() { @Override//from www .j av a 2s . c o m protected Void doInBackground(Integer... params) { try { DatagramSocket socket = new DatagramSocket(); socket.setBroadcast(true); String data = opts.toString(); DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(), getBroadcastAddress(), opts.getInt("port")); socket.send(packet); Log.d(TAG, "Sent packet"); byte[] buf = new byte[1024]; packet = new DatagramPacket(buf, buf.length); socket.receive(packet); String result = new String(buf, 0, packet.getLength()); Log.d(TAG, "Got response packet of " + packet.getLength() + " bytes: " + result); callbackContext.success(result); } catch (Exception e) { callbackContext.error(e.getMessage()); Log.e(TAG, "Exception while listening for server broadcast"); e.printStackTrace(); } return null; } }.execute(); }
From source file:poisondog.net.udp.DatagramMission.java
public DatagramResponse execute(DatagramParameter parameter) throws IOException { DatagramSocket socket = new DatagramSocket(null); socket.setReuseAddress(true);//ww w . j a va2s. c o m socket.setBroadcast(parameter.getBroadcast()); if (parameter.getTimeout() > 0) socket.setSoTimeout(parameter.getTimeout()); String data = IOUtils.toString(parameter.getInputStream()); DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length()); packet.setAddress(InetAddress.getByName(parameter.getHost())); packet.setPort(parameter.getPort()); socket.send(packet); DatagramResponse response = new DatagramResponse(parameter.getResponseLength()); DatagramPacket responsePacket = new DatagramPacket(response.getContent(), response.getContent().length); socket.receive(responsePacket); response.setAddress(responsePacket.getAddress().getHostAddress()); response.setPacketLength(responsePacket.getLength()); socket.close(); return response; }