List of usage examples for java.net DatagramSocket receive
public synchronized void receive(DatagramPacket p) throws IOException
From source file:com.byteatebit.nbserver.simple.TestSimpleNbServer.java
@Test public void testUdpEchoServer() throws IOException { SimpleNbServer simpleNbServer = SimpleNbServer.Builder.builder() .withConfig(/* w w w. j av a2s. co m*/ SimpleNbServerConfig.builder().withListenAddress("localhost").withListenPort(1111).build()) .withConnectorFactory(UdpConnectorFactory.Builder.builder() .withDatagramMessageHandlerFactory(new UdpServiceFactory()).build()) .build(); simpleNbServer.start(); String message1 = "this is message1"; String message2 = "this is message2"; String message3 = "quit"; try { DatagramSocket socket = new DatagramSocket(); SocketAddress address = new InetSocketAddress("localhost", 1111); // message 1 byte[] payload1 = message1.getBytes(StandardCharsets.UTF_8); DatagramPacket packet = new DatagramPacket(payload1, payload1.length, address); socket.send(packet); byte[] response = new byte[50]; DatagramPacket responsePacket = new DatagramPacket(response, response.length); socket.receive(responsePacket); String messageRead = new String(responsePacket.getData(), 0, responsePacket.getLength()); Assert.assertEquals(message1, messageRead); // message2 byte[] payload2 = message2.getBytes(StandardCharsets.UTF_8); DatagramPacket packet2 = new DatagramPacket(payload2, payload2.length, address); socket.send(packet2); responsePacket = new DatagramPacket(response, response.length); socket.receive(responsePacket); messageRead = new String(responsePacket.getData(), 0, responsePacket.getLength()); Assert.assertEquals(message2, messageRead); // message3 byte[] payload3 = message3.getBytes(StandardCharsets.UTF_8); DatagramPacket packet3 = new DatagramPacket(payload3, payload3.length, address); socket.send(packet3); responsePacket = new DatagramPacket(response, response.length); socket.receive(responsePacket); messageRead = new String(responsePacket.getData(), 0, responsePacket.getLength()); Assert.assertEquals("goodbye", messageRead); } finally { simpleNbServer.shutdown(); } }
From source file:org.openhab.binding.edimax.internal.UDPDiscoverer.java
private EdimaxDevice[] discover() throws SocketException, UnknownHostException, IOException { List<EdimaxDevice> discoveredDevices = new ArrayList<EdimaxDevice>(); DatagramSocket serverSocket = null; try {//from w w w . j av a2 s . c o m serverSocket = new DatagramSocket(12346); // choose random port, // because with empty // port sometimes error // occures. // send UDP broadcast InetAddress ipAddress = InetAddress.getByName("255.255.255.255"); byte[] sendData = DISCOVERY_BYTES; DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress, 20560); serverSocket.send(sendPacket); // receive serverSocket.setSoTimeout(1000 * 5); byte[] receiveData = new byte[1024]; try { while (true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String sentence = new String(receivePacket.getData()); if (!StringUtils.isEmpty(sentence) && sentence.contains("EDIMAX")) { byte[] mac = new byte[6]; System.arraycopy(receivePacket.getData(), 0, mac, 0, 6); String encodedMAC = Hex.encodeHexString(mac).toUpperCase(); InetAddress discoveredIp = receivePacket.getAddress(); EdimaxDevice dev = new EdimaxDevice(); dev.setIp(discoveredIp.getHostAddress()); dev.setMac(encodedMAC); discoveredDevices.add(dev); } } } catch (SocketTimeoutException e) { // intended to happen } } finally { if (serverSocket != null) { serverSocket.close(); } } return discoveredDevices.toArray(new EdimaxDevice[discoveredDevices.size()]); }
From source file:org.eclipse.smarthome.binding.wemo.discovery.WemoDiscoveryService.java
public void sendWemoDiscoveryMessage() { logger.debug("wemoDiscovery() is called!"); try {//w ww .j a v a 2 s. c o m InetAddress localhost = InetAddress.getLocalHost(); InetSocketAddress srcAddress = new InetSocketAddress(localhost, SSDP_SEARCH_PORT); InetSocketAddress dstAddress = new InetSocketAddress(InetAddress.getByName(SSDP_IP), SSDP_PORT); // Request-Packet-Constructor StringBuffer discoveryMessage = new StringBuffer(); discoveryMessage.append("M-SEARCH * HTTP/1.1\r\n"); discoveryMessage.append("HOST: " + SSDP_IP + ":" + SSDP_PORT + "\r\n"); discoveryMessage.append("ST: upnp:rootdevice\r\n"); discoveryMessage.append("MAN: \"ssdp:discover\"\r\n"); discoveryMessage.append("MX: 5\r\n"); discoveryMessage.append("\r\n"); logger.trace("Request: {}", discoveryMessage.toString()); byte[] discoveryMessageBytes = discoveryMessage.toString().getBytes(); DatagramPacket discoveryPacket = new DatagramPacket(discoveryMessageBytes, discoveryMessageBytes.length, dstAddress); // Send multi-cast packet MulticastSocket multicast = null; try { multicast = new MulticastSocket(null); multicast.bind(srcAddress); logger.trace("Source-Address = '{}'", srcAddress); multicast.setTimeToLive(4); logger.debug("Send multicast request."); multicast.send(discoveryPacket); } finally { logger.trace("Multicast ends. Close connection."); multicast.disconnect(); multicast.close(); } // Response-Listener DatagramSocket wemoReceiveSocket = null; DatagramPacket receivePacket = null; try { wemoReceiveSocket = new DatagramSocket(SSDP_SEARCH_PORT); wemoReceiveSocket.setSoTimeout(TIMEOUT); logger.debug("Send datagram packet."); wemoReceiveSocket.send(discoveryPacket); while (true) { try { receivePacket = new DatagramPacket(new byte[1536], 1536); wemoReceiveSocket.receive(receivePacket); final String message = new String(receivePacket.getData()); logger.trace("Received message: {}", message); new Thread(new Runnable() { @Override public void run() { String label = "WeMo Device"; String wemoUDN = null; String wemoLocation = null; String wemoFriendlyName = null; String wemoModelName = null; ThingUID uid = null; if (message != null) { if (message.contains("Socket-1_0") || message.contains("Insight-1_0") || message.contains("Motion-1_0") || message.contains("Lightswitch-1_0")) { wemoUDN = StringUtils.substringBetween(message, "USN: uuid:", "::upnp:rootdevice"); logger.debug("Wemo device with UDN '{}' found", wemoUDN); wemoLocation = StringUtils.substringBetween(message, "LOCATION: ", "/setup.xml"); if (wemoLocation != null) { try { int timeout = 5000; String response = HttpUtil.executeUrl("GET", wemoLocation + "/setup.xml", timeout); wemoFriendlyName = StringUtils.substringBetween(response, "<friendlyName>", "</friendlyName>"); logger.debug("Wemo device '{}' found at '{}'", wemoFriendlyName, wemoLocation); wemoModelName = StringUtils.substringBetween(response, "<modelName>", "</modelName>"); logger.trace("Wemo device '{}' has model name '{}'", wemoFriendlyName, wemoModelName); label = "Wemo" + wemoModelName; switch (wemoModelName) { case "Socket": logger.debug( "Creating ThingUID for device model '{}' with UDN '{}'", wemoModelName, wemoUDN); uid = new ThingUID(WEMO_SOCKET_TYPE_UID, wemoUDN); break; case "Insight": logger.trace( "Creating ThingUID for device model '{}' with UDN '{}'", wemoModelName, wemoUDN); uid = new ThingUID(WEMO_INSIGHT_TYPE_UID, wemoUDN); break; case "LightSwitch": logger.trace( "Creating ThingUID for device model '{}' with UDN '{}'", wemoModelName, wemoUDN); uid = new ThingUID(WEMO_LIGHTSWITCH_TYPE_UID, wemoUDN); break; case "Motion": logger.trace( "Creating ThingUID for device model '{}' with UDN '{}'", wemoModelName, wemoUDN); uid = new ThingUID(WEMO_MOTION_TYPE_UID, wemoUDN); break; } Map<String, Object> properties = new HashMap<>(4); properties.put(UDN, wemoUDN); properties.put(LOCATION, wemoLocation); DiscoveryResult result = DiscoveryResultBuilder.create(uid) .withProperties(properties).withLabel(label).build(); thingDiscovered(result); } catch (Exception te) { logger.error("Could not discover WeMo device", te); } } } } } }).start(); } catch (SocketTimeoutException e) { logger.debug("Message receive timed out."); break; } } } finally { if (wemoReceiveSocket != null) { wemoReceiveSocket.disconnect(); wemoReceiveSocket.close(); } } } catch (Exception e) { logger.error("Could not send Wemo device discovery", e); } }
From source file:us.nineworlds.serenity.core.services.GDMService.java
@Override protected void onHandleIntent(Intent intent) { try {/*from w ww .ja va2 s. c o m*/ DatagramSocket socket = new DatagramSocket(32414); socket.setBroadcast(true); String data = "M-SEARCH * HTTP/1.1\r\n\r\n"; DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(), useMultiCastAddress(), 32414); // DatagramPacket packet = new DatagramPacket(data.getBytes(), // data.length(), getBroadcastAddress(), 32414); socket.send(packet); Log.d("GDMService", "Search Packet Broadcasted"); byte[] buf = new byte[256]; packet = new DatagramPacket(buf, buf.length); socket.setSoTimeout(2000); boolean listening = true; while (listening) { try { socket.receive(packet); String packetData = new String(packet.getData()); if (packetData.contains("HTTP/1.0 200 OK")) { Log.d("GDMService", "PMS Packet Received"); // Broadcast Received Packet Intent packetBroadcast = new Intent(GDMService.MSG_RECEIVED); packetBroadcast.putExtra("data", packetData); packetBroadcast.putExtra("ipaddress", packet.getAddress().toString()); LocalBroadcastManager.getInstance(this).sendBroadcast(packetBroadcast); } } catch (SocketTimeoutException e) { Log.d("GDMService", "Socket Timeout"); socket.close(); listening = false; Intent socketBroadcast = new Intent(GDMService.SOCKET_CLOSED); LocalBroadcastManager.getInstance(this).sendBroadcast(socketBroadcast); } } } catch (IOException e) { Log.e("GDMService", e.toString()); } }
From source file:org.springframework.integration.ip.udp.UdpChannelAdapterTests.java
@SuppressWarnings("unchecked") @Test//from ww w .j a v a 2 s. co m public void testUnicastReceiverWithReply() throws Exception { QueueChannel channel = new QueueChannel(2); int port = SocketUtils.findAvailableUdpSocket(); UnicastReceivingChannelAdapter adapter = new UnicastReceivingChannelAdapter(port); adapter.setOutputChannel(channel); adapter.start(); SocketTestUtils.waitListening(adapter); Message<byte[]> message = MessageBuilder.withPayload("ABCD".getBytes()).build(); DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper(); DatagramPacket packet = mapper.fromMessage(message); packet.setSocketAddress(new InetSocketAddress("localhost", port)); final DatagramSocket socket = new DatagramSocket(SocketUtils.findAvailableUdpSocket()); socket.send(packet); final AtomicReference<DatagramPacket> theAnswer = new AtomicReference<DatagramPacket>(); final CountDownLatch receiverReadyLatch = new CountDownLatch(1); final CountDownLatch replyReceivedLatch = new CountDownLatch(1); //main thread sends the reply using the headers, this thread will receive it Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { DatagramPacket answer = new DatagramPacket(new byte[2000], 2000); try { receiverReadyLatch.countDown(); socket.receive(answer); theAnswer.set(answer); replyReceivedLatch.countDown(); } catch (IOException e) { e.printStackTrace(); } } }); Message<byte[]> receivedMessage = (Message<byte[]>) channel.receive(2000); assertEquals(new String(message.getPayload()), new String(receivedMessage.getPayload())); String replyString = "reply:" + System.currentTimeMillis(); byte[] replyBytes = replyString.getBytes(); DatagramPacket reply = new DatagramPacket(replyBytes, replyBytes.length); reply.setSocketAddress( new InetSocketAddress((String) receivedMessage.getHeaders().get(IpHeaders.IP_ADDRESS), (Integer) receivedMessage.getHeaders().get(IpHeaders.PORT))); assertTrue(receiverReadyLatch.await(10, TimeUnit.SECONDS)); new DatagramSocket().send(reply); assertTrue(replyReceivedLatch.await(10, TimeUnit.SECONDS)); DatagramPacket answerPacket = theAnswer.get(); assertNotNull(answerPacket); assertEquals(replyString, new String(answerPacket.getData(), 0, answerPacket.getLength())); }
From source file:org.apache.webdav.lib.NotificationListener.java
/** * /*w w w . j av a 2s . com*/ * @param host The ip-address on which the udp or http-server is running (e.g. "localhost") * @param port The port where the udp or http-server is listening on (e.g. 4444) * @param repositoryHost The ip-adress of the WebDAV-repository * @param repositoryPort The port of the WebDAV-repository (e.g. 8080) * @param protocol The protocol that should be used to connect to the WebDAV-repository (http or https) * @param credentials The credentials which are used to connect to the WebDAV-repository * @param repositoryDomain The repository domain (e.g. "/slide") * @param pollInterval The poll interval that will be used if no notifications are revieved via UDP/TCP * @param udp If set to true, UDP server will be started, otherwise TCP server (must match the repository notification mode) */ public NotificationListener(String host, int port, String repositoryHost, int repositoryPort, Protocol protocol, Credentials credentials, String repositoryDomain, int pollInterval, boolean udp) { this.credentials = credentials; this.notificationHost = host; this.notificationPort = port; this.repositoryHost = repositoryHost; this.repositoryPort = repositoryPort; this.protocol = protocol; this.repositoryDomain = repositoryDomain; this.udp = udp; if (udp) { Thread listenerThread = new Thread(new Runnable() { public void run() { DatagramSocket serverSocket = null; try { serverSocket = new DatagramSocket(notificationPort); while (true) { byte[] buf = new byte[256]; DatagramPacket packet = new DatagramPacket(buf, buf.length); serverSocket.receive(packet); BufferedReader reader = new BufferedReader( new InputStreamReader(new ByteArrayInputStream(buf))); parseNotification(reader); } } catch (IOException e) { logger.log(Level.SEVERE, "Error while listening to socket", e); } } }); listenerThread.setDaemon(true); listenerThread.start(); } else { Thread listenerThread = new Thread(new Runnable() { public void run() { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(notificationPort); while (true) { new ConnectionThread(serverSocket.accept()).start(); } } catch (IOException e) { logger.log(Level.SEVERE, "Error while listening to socket", e); } } }); listenerThread.setDaemon(true); listenerThread.start(); } TimerTask poll = new TimerTask() { public void run() { if (subscribersAsString != null) { poll(subscribersAsString); } } }; timer.schedule(poll, pollInterval, pollInterval); }
From source file:Reflector.java
private void listen(DatagramSocket ds) { // loop forever listening to packets, when they // arrive log them and notify all interested threads. byte[] buffer; DatagramPacket packet;//w w w. ja v a 2 s. com while (true) { try { buffer = new byte[MAX_PACKET_SIZE]; packet = new DatagramPacket(buffer, buffer.length); ds.receive(packet); logger.log("Packet received, " + packet.getLength() + " bytes"); eventNotify(packet); } catch (IOException e) { System.err.println("Error receiving packet\n"); e.printStackTrace(); } } }
From source file:com.mobiperf.measurements.RRCTask.java
/** * Send a single packet of the size indicated and wait for a response. * //from w w w . j ava 2s .com * After 7000 ms, time out and return a value of -1 (meaning no response). Otherwise, return the * time from when the packet was sent to when a response was returned by the echo server. * * @param serverAddr Echo server to calculate round trip * @param size size of packet to send in bytes * @param rcvSize size of packets sent from the echo server * @param port where the echo server is listening * @return The round trip time for the packet * @throws IOException */ public static long sendPacket(InetAddress serverAddr, int size, int rcvSize, int port) throws IOException { long startTime = 0; byte[] buf = new byte[size]; byte[] rcvBuf = new byte[rcvSize]; long dataConsumedThisTask = 0; DatagramSocket socket = new DatagramSocket(); DatagramPacket packetRcv = new DatagramPacket(rcvBuf, rcvBuf.length); dataConsumedThisTask += (size + rcvSize); DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port); try { socket.setSoTimeout(7000); startTime = System.currentTimeMillis(); Logger.d("Sending packet, waiting for response "); socket.send(packet); socket.receive(packetRcv); } catch (SocketTimeoutException e) { Logger.d("Timed out, trying again"); socket.close(); return -1; } long endTime = System.currentTimeMillis(); Logger.d("Sending complete: " + endTime); incrementData(dataConsumedThisTask); return endTime - startTime; }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Attempts to retrieve the job managers address in the network through an * IP broadcast. This method should be called by the task manager. * //w w w . ja va2s .c o m * @return the socket address of the job manager in the network * @throws DiscoveryException * thrown if the job manager's socket address could not be * discovered */ public static InetSocketAddress getJobManagerAddress() throws DiscoveryException { final int magicNumber = GlobalConfiguration.getInteger(MAGICNUMBER_KEY, DEFAULT_MAGICNUMBER); final int discoveryPort = GlobalConfiguration.getInteger(DISCOVERYPORT_KEY, DEFAULT_DISCOVERYPORT); InetSocketAddress jobManagerAddress = null; DatagramSocket socket = null; try { final Set<InetAddress> targetAddresses = getBroadcastAddresses(); if (targetAddresses.isEmpty()) { throw new DiscoveryException("Could not find any broadcast addresses available to this host"); } 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 lookupRequest = createJobManagerLookupRequestPacket(magicNumber); for (InetAddress broadcast : targetAddresses) { lookupRequest.setAddress(broadcast); lookupRequest.setPort(discoveryPort); LOG.debug("Sending discovery request to " + lookupRequest.getSocketAddress()); socket.send(lookupRequest); } try { socket.receive(responsePacket); } catch (SocketTimeoutException ste) { LOG.debug("Timeout wainting for discovery reply. Retrying..."); continue; } if (!isPacketForUs(responsePacket, magicNumber)) { LOG.debug("Received packet which is not destined to this Nephele setup"); continue; } final int packetTypeID = getPacketTypeID(responsePacket); if (packetTypeID != JM_LOOKUP_REPLY_ID) { LOG.debug("Received unexpected packet type " + packetTypeID + ", discarding... "); continue; } final int ipcPort = extractIpcPort(responsePacket); // Replace port from discovery service with the actual RPC port // of the job manager if (USE_IPV6) { // TODO: No connection possible unless we remove the scope identifier if (responsePacket.getAddress() instanceof Inet6Address) { try { jobManagerAddress = new InetSocketAddress( InetAddress.getByAddress(responsePacket.getAddress().getAddress()), ipcPort); } catch (UnknownHostException e) { throw new DiscoveryException(StringUtils.stringifyException(e)); } } else { throw new DiscoveryException(responsePacket.getAddress() + " is not a valid IPv6 address"); } } else { jobManagerAddress = new InetSocketAddress(responsePacket.getAddress(), ipcPort); } LOG.debug("Discovered job manager at " + jobManagerAddress); break; } } catch (IOException ioe) { throw new DiscoveryException(ioe.toString()); } finally { if (socket != null) { socket.close(); } } if (jobManagerAddress == null) { LOG.debug("Unable to discover Jobmanager via IP broadcast"); throw new DiscoveryException("Unable to discover JobManager via IP broadcast!"); } return jobManagerAddress; }
From source file:com.mobilyzer.measurements.RRCTask.java
/** * Send a single packet of the size indicated and wait for a response. * /*from w w w. j a v a 2 s . co m*/ * After 7000 ms, time out and return a value of -1 (meaning no response). Otherwise, return the * time from when the packet was sent to when a response was returned by the echo server. * * @param serverAddr Echo server to calculate round trip * @param size size of packet to send in bytes * @param rcvSize size of packets sent from the echo server * @param port where the echo server is listening * @return The round trip time for the packet * @throws IOException */ public static long sendPacket(InetAddress serverAddr, int size, int rcvSize, int port) throws IOException { long startTime = 0; byte[] buf = new byte[size]; byte[] rcvBuf = new byte[rcvSize]; DatagramSocket socket = new DatagramSocket(); DatagramPacket packetRcv = new DatagramPacket(rcvBuf, rcvBuf.length); DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port); try { socket.setSoTimeout(7000); startTime = System.currentTimeMillis(); Logger.d("Sending packet, waiting for response "); socket.send(packet); socket.receive(packetRcv); } catch (SocketTimeoutException e) { Logger.d("Timed out, trying again"); socket.close(); return -1; } long endTime = System.currentTimeMillis(); Logger.d("Sending complete: " + endTime); return endTime - startTime; }