List of usage examples for java.net DatagramSocket receive
public synchronized void receive(DatagramPacket p) throws IOException
From source file:gravity.android.discovery.DiscoveryClient.java
public static ArrayList<DiscoveryServerInfo> findServer(WifiManager mWifi, int port, String token) { ArrayList<DiscoveryServerInfo> ret = new ArrayList<DiscoveryServerInfo>(); try {/* w ww.j a v a 2s . c o m*/ DatagramSocket clientSocket = new DatagramSocket(); clientSocket.setBroadcast(true); InetAddress IPAddress = Utils.getBroadcastAddress(mWifi); Log.v("DISCOVERY_CLIENT", "broadcast addr " + IPAddress.getHostAddress()); byte[] receiveData = new byte[2048]; byte[] sendData = new byte[128]; sendData = token.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); Log.v("DISCOVERY_CLIENT", "sent " + token); clientSocket.send(sendPacket); long t1 = System.currentTimeMillis(); while (System.currentTimeMillis() - t1 <= 4000) // 4 secondi { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); try { clientSocket.setSoTimeout(500); clientSocket.receive(receivePacket); if (receivePacket.getAddress() != null && receivePacket.getAddress().getHostAddress() != null) { String discovered_name, discovered_ip; int discovered_port; String received = new String(receivePacket.getData()); if (received != null) { received = received.trim().substring(0, receivePacket.getLength()).trim(); Log.d("Recieved Msg Packet:", received); //StringTokenizer st = new StringTokenizer(received, ","); //Gravity Code JSONObject recievedJson = new JSONObject(received); try { //discovered_name = st.nextToken(); discovered_name = recievedJson.getString("name"); //Gravity code discovered_ip = receivePacket.getAddress().getHostAddress(); //discovered_port = Integer.parseInt(st.nextToken()); discovered_port = recievedJson.getInt("port_to_share"); //Gravity code Log.v("DISCOVERY_CLIENT", "discovered " + discovered_name + ", " + discovered_ip + ":" + discovered_port); boolean add = true; if (ret.size() > 0) { for (DiscoveryServerInfo dsi : ret) { if (dsi != null && dsi.ip.equals(discovered_ip)) { add = false; break; } } } if (add) { ret.add(new DiscoveryServerInfo(discovered_name, discovered_ip, discovered_port)); } } catch (NoSuchElementException nsee) { Log.v("DISCOVERY_CLIENT", nsee.getLocalizedMessage()); } } } } catch (SocketTimeoutException tex) { /* ignored */ } } clientSocket.close(); } catch (Exception ex) { ex.printStackTrace(); Log.e("DISCOVERY_CLIENT", ex.toString()); } return ret; }
From source file:org.vesalainen.net.sntp.SNTPServer.java
@Override public void run() { try {/*from w w w.j a v a 2s . c o m*/ DatagramSocket socket = new DatagramSocket(123); byte[] buffer = new byte[1024]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); while (true) { socket.receive(packet); NtpV3Impl msg = new NtpV3Impl(); msg.setDatagramPacket(packet); System.err.println(msg); } } catch (SocketException ex) { Logger.getLogger(SNTPServer.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(SNTPServer.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:werewolf_client.Werewolf_Client.java
public void recvFromClient(String adr, int p) throws SocketException, IOException { DatagramSocket recv = new DatagramSocket(p); byte[] recvData = new byte[1024]; while (true) { DatagramPacket recvPacket = new DatagramPacket(recvData, recvData.length); recv.receive(recvPacket); String s = new String(recvPacket.getData(), 0, recvPacket.getLength()); System.out.println("ReceivedD\n" + s); }//from w ww .j a v a 2 s. c o m }
From source file:org.springframework.integration.ip.udp.DatagramPacketSendingHandlerTests.java
@Test public void verifySend() throws Exception { final int testPort = SocketUtils.findAvailableUdpSocket(); byte[] buffer = new byte[8]; final DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length); final CountDownLatch latch = new CountDownLatch(1); Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { DatagramSocket socket = new DatagramSocket(testPort); socket.receive(receivedPacket); latch.countDown();// w ww .j a v a 2 s. c o m socket.close(); } catch (Exception e) { e.printStackTrace(); } } }); Thread.sleep(1000); UnicastSendingMessageHandler handler = new UnicastSendingMessageHandler("localhost", testPort); String payload = "foo"; handler.handleMessage(MessageBuilder.withPayload(payload).build()); assertTrue(latch.await(3000, TimeUnit.MILLISECONDS)); byte[] src = receivedPacket.getData(); int length = receivedPacket.getLength(); int offset = receivedPacket.getOffset(); byte[] dest = new byte[length]; System.arraycopy(src, offset, dest, 0, length); assertEquals(payload, new String(dest)); handler.shutDown(); }
From source file:org.springframework.integration.ip.udp.DatagramPacketSendingHandlerTests.java
@Test public void verifySendWithAck() throws Exception { final List<Integer> openPorts = SocketUtils.findAvailableUdpSockets(SocketUtils.getRandomSeedPort(), 2); final int testPort = openPorts.get(0); final int ackPort = openPorts.get(1); byte[] buffer = new byte[1000]; final DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length); final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); UnicastSendingMessageHandler handler = new UnicastSendingMessageHandler("localhost", testPort, true, true, "localhost", ackPort, 5000); handler.afterPropertiesSet();/* w ww .j av a 2s. c o m*/ Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { DatagramSocket socket = new DatagramSocket(testPort); latch1.countDown(); socket.receive(receivedPacket); socket.close(); DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper(); mapper.setAcknowledge(true); mapper.setLengthCheck(true); Message<byte[]> message = mapper.toMessage(receivedPacket); Object id = message.getHeaders().get(IpHeaders.ACK_ID); byte[] ack = id.toString().getBytes(); DatagramPacket ackPack = new DatagramPacket(ack, ack.length, new InetSocketAddress("localHost", ackPort)); DatagramSocket out = new DatagramSocket(); out.send(ackPack); out.close(); latch2.countDown(); } catch (Exception e) { e.printStackTrace(); } } }); latch1.await(3000, TimeUnit.MILLISECONDS); String payload = "foobar"; handler.handleMessage(MessageBuilder.withPayload(payload).build()); assertTrue(latch2.await(10000, TimeUnit.MILLISECONDS)); byte[] src = receivedPacket.getData(); int length = receivedPacket.getLength(); int offset = receivedPacket.getOffset(); byte[] dest = new byte[6]; System.arraycopy(src, offset + length - 6, dest, 0, 6); assertEquals(payload, new String(dest)); handler.shutDown(); }
From source file:com.kecso.socket.ServerSocketControl.java
@Override public void run() { DatagramSocket sock = null; try {//w ww. j a v a2s .c o m sock = new DatagramSocket(8888); sock.setSoTimeout(1000); byte[] buffer = new byte[65536]; DatagramPacket incoming = new DatagramPacket(buffer, buffer.length); while (!Thread.currentThread().isInterrupted()) { try { sock.receive(incoming); byte[] data = incoming.getData(); this.udpMessage = SerializationUtils.deserialize(data); byte[] response = SerializationUtils.serialize( this.output != null ? new UdpResponse((float) output.getSpeed(), (float) output.getVerticalSpeed(), (float) output.getAltitude(), (float) output.getRpm()) : null); DatagramPacket dp = new DatagramPacket(response, response.length, incoming.getAddress(), incoming.getPort()); sock.send(dp); } catch (SocketTimeoutException e) { } } } catch (Exception e) { System.err.println("IOException " + e); } finally { if (sock != null) { sock.close(); } } }
From source file:org.hyperic.util.ntp.NtpClient.java
public NtpResponse getResponse() throws SocketException, UnknownHostException, IOException { DatagramSocket socket = new DatagramSocket(); socket.setSoTimeout(this.timeout); InetAddress address = InetAddress.getByName(this.hostname); byte[] data = NtpResponse.getRequestBytes(); DatagramPacket packet = new DatagramPacket(data, data.length, address, this.port); socket.send(packet);/* w w w . j a v a 2 s . co m*/ packet = new DatagramPacket(data, data.length); socket.receive(packet); NtpResponse response = NtpResponse.decodeResponse(now(), packet.getData()); return response; }
From source file:org.mule.test.firewall.FirewallTestCase.java
protected void doTestUdp(InetAddress address, int port) throws Exception { try {// w ww . ja v a 2s .c om logger.debug("Testing UDP on " + addressToString(address, port)); DatagramSocket server = openUdpServer(address, port); DatagramSocket client = openUdpClient(); client.send(new DatagramPacket(new byte[] { 1 }, 1, address, port)); DatagramPacket packet = new DatagramPacket(new byte[1], 1); server.receive(packet); assertEquals("Failed to send packet via " + addressToString(address, port), 1, packet.getData()[0]); client.close(); server.close(); } catch (Exception e) { logger.error("Error while attempting UDP message on " + addressToString(address, port)); throw e; } }
From source file:com.webobjects.monitor.application.HostsPage.java
private boolean hostMeetsMinimumVersion(InetAddress anAddress) { byte[] versionRequest; try {//from w w w .ja va 2 s.co m versionRequest = ("womp://queryVersion").getBytes(CharEncoding.UTF_8); } catch (UnsupportedEncodingException uee) { versionRequest = ("womp://queryVersion").getBytes(); } DatagramPacket outgoingPacket = new DatagramPacket(versionRequest, versionRequest.length, anAddress, WOApplication.application().lifebeatDestinationPort()); byte[] mbuffer = new byte[1000]; DatagramPacket incomingPacket = new DatagramPacket(mbuffer, mbuffer.length); DatagramSocket socket = null; try { socket = new DatagramSocket(); socket.send(outgoingPacket); incomingPacket.setLength(mbuffer.length); socket.setSoTimeout(2000); socket.receive(incomingPacket); String reply = new String(incomingPacket.getData()); if (reply.startsWith("womp://replyVersion/")) { int lastIndex = reply.lastIndexOf(":webObjects"); lastIndex += 11; String version = reply.substring(lastIndex); if (version.equals("4.5")) { return false; } } else { return false; } } catch (InterruptedIOException iioe) { return true; } catch (SocketException se) { return true; } catch (Throwable e) { return false; } finally { if (socket != null) { socket.close(); } } return true; }
From source file:net.sourceforge.vulcan.ant.receiver.UdpEventSource.java
@Override public void run() { final DatagramSocket socket = openSocket(); active = true;//from w w w . j a v a 2s.com synchronized (this) { notifyAll(); } final byte[] buffer = new byte[8192]; try { final DatagramPacket packet = new DatagramPacket(buffer, buffer.length); while (active) { try { socket.receive(packet); final AntEventSummary summary = deserialize(packet.getData()); fireEvent(summary); } catch (SocketTimeoutException e) { continue; } catch (Exception e) { handleException(e); } } } finally { socket.close(); } }