List of usage examples for java.net DatagramPacket DatagramPacket
public DatagramPacket(byte buf[], int length, InetAddress address, int port)
From source file:com.neophob.sematrix.core.output.E1_31Device.java
/** * //from w ww .j a va 2s . c o m * @param controller */ public E1_31Device(ApplicationConfigurationHelper ph, int nrOfScreens) { super(OutputDeviceEnum.E1_31, ph, 8, nrOfScreens); this.displayOptions = ph.getE131Device(); //Get dmx specific config this.pixelsPerUniverse = ph.getE131PixelsPerUniverse(); try { String ip = ph.getE131Ip(); String sendMode = "Unicast"; if (StringUtils.startsWith(ip, MULTICAST_START)) { this.sendMulticast = true; sendMode = "Multicast"; } this.targetAdress = InetAddress.getByName(ip); this.firstUniverseId = ph.getE131StartUniverseId(); calculateNrOfUniverse(); packet = new DatagramPacket(new byte[0], 0, targetAdress, E1_31DataPacket.E131_PORT); dsocket = new DatagramSocket(); this.initialized = true; LOG.log(Level.INFO, "E1.31 device initialized, send mode: " + sendMode + ", use " + this.displayOptions.size() + " panels"); } catch (Exception e) { LOG.log(Level.WARNING, "failed to initialize E1.31 device", e); } }
From source file:network.UDPServer.java
public void sendMessage(Message message, InetAddress remoteAddress, int remotePort) { byte tempBuffer[] = SerializationUtils.serialize(message); final DatagramPacket sendPacket = new DatagramPacket(tempBuffer, tempBuffer.length, remoteAddress, remotePort);// www.jav a2 s .c o m executorService.execute(new Runnable() { public void run() { try { //System.out.println("Send UDP message!"); socket.send(sendPacket); } catch (Exception e) { e.printStackTrace(); } } }); }
From source file:org.eredlab.g4.ccl.net.TimeUDPClient.java
/*** * Retrieves the time from the specified server and port and * returns it. The time is the number of seconds since * 00:00 (midnight) 1 January 1900 GMT, as specified by RFC 868. * This method reads the raw 32-bit big-endian * unsigned integer from the server, converts it to a Java long, and * returns the value./* w ww . j ava 2s. com*/ * <p> * @param host The address of the server. * @param port The port of the service. * @return The time value retrieved from the server. * @exception IOException If an error occurs while retrieving the time. ***/ public long getTime(InetAddress host, int port) throws IOException { long time; DatagramPacket sendPacket, receivePacket; sendPacket = new DatagramPacket(__dummyData, __dummyData.length, host, port); receivePacket = new DatagramPacket(__timeData, __timeData.length); _socket_.send(sendPacket); _socket_.receive(receivePacket); time = 0L; time |= (((__timeData[0] & 0xff) << 24) & 0xffffffffL); time |= (((__timeData[1] & 0xff) << 16) & 0xffffffffL); time |= (((__timeData[2] & 0xff) << 8) & 0xffffffffL); time |= ((__timeData[3] & 0xff) & 0xffffffffL); return time; }
From source file:org.openhab.binding.wol.internal.WolBinding.java
private void sendWolPacket(WolBindingConfig config) { if (config == null) { logger.error("given parameter 'config' must not be null"); return;/*from www . j a v a2 s .c o m*/ } InetAddress address = config.address; byte[] macBytes = config.macBytes; try { byte[] bytes = fillMagicBytes(macBytes); DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, PORT); DatagramSocket socket = new DatagramSocket(); socket.send(packet); socket.close(); logger.info("Wake-on-LAN packet sent [broadcastIp={}, macaddress={}]", address.getHostName(), String.valueOf(Hex.encodeHex(macBytes))); } catch (Exception e) { logger.error("Failed to send Wake-on-LAN packet [broadcastIp=" + address.getHostAddress() + ", macaddress=" + String.valueOf(Hex.encodeHex(macBytes)) + "]", e); } }
From source file:org.apache.jcs.auxiliary.lateral.socket.udp.LateralUDPSender.java
/** Description of the Method */ public void send(LateralElementDescriptor led) throws IOException { log.debug("sending LateralElementDescriptor"); try {// w ww. ja v a2s. c om final MyByteArrayOutputStream byteStream = new MyByteArrayOutputStream(); final ObjectOutputStream objectStream = new ObjectOutputStream(byteStream); objectStream.writeObject(led); objectStream.flush(); final byte[] bytes = byteStream.getBytes(); final DatagramPacket packet = new DatagramPacket(bytes, bytes.length, m_multicastAddress, m_multicastPort); m_localSocket.send(packet); } catch (IOException e) { log.error("Error sending message", e); throw e; } }
From source file:edu.uic.udptransmit.UDPTransmit.java
@Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { if ("initialize".equals(action)) { final String host = args.getString(0); final int port = args.getInt(1); // Run the UDP transmitter initialization on its own thread (just in case, see sendMessage comment) cordova.getThreadPool().execute(new Runnable() { public void run() { this.initialize(host, port, callbackContext); }/* w w w . j av a 2 s. c o m*/ private void initialize(String host, int port, CallbackContext callbackContext) { boolean successResolvingIPAddress = false; // create packet InetAddress address = null; try { // 'host' can be a ddd.ddd.ddd.ddd or named URL, so doesn't always resolve address = InetAddress.getByName(host); successResolvingIPAddress = true; } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } // If we were able to resolve the IP address from the host name, we're good to try to initialize if (successResolvingIPAddress) { byte[] bytes = new byte[0]; datagramPacket = new DatagramPacket(bytes, 0, address, port); // create socket try { datagramSocket = new DatagramSocket(); successInitializingTransmitter = true; } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (successInitializingTransmitter) callbackContext.success( "Success initializing UDP transmitter using datagram socket: " + datagramSocket); else callbackContext.error( "Error initializing UDP transmitter using datagram socket: " + datagramSocket); } }); return true; } else if ("sendMessage".equals(action)) { final String message = args.getString(0); // Run the UDP transmission on its own thread (it fails on some Android environments if run on the same thread) cordova.getThreadPool().execute(new Runnable() { public void run() { this.sendMessage(message, callbackContext); } private void sendMessage(String data, CallbackContext callbackContext) { boolean messageSent = false; // Only attempt to send a packet if the transmitter initialization was successful if (successInitializingTransmitter) { byte[] bytes = data.getBytes(); datagramPacket.setData(bytes); try { datagramSocket.send(datagramPacket); messageSent = true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (messageSent) callbackContext.success("Success transmitting UDP packet: " + datagramPacket); else callbackContext.error("Error transmitting UDP packet: " + datagramPacket); } }); return true; } else if ("resolveHostName".equals(action)) { final String url = args.getString(0); // Run the UDP transmission on its own thread (it fails on some Android environments if run on the same thread) cordova.getThreadPool().execute(new Runnable() { public void run() { this.resolveHostName(url, callbackContext); } private void resolveHostName(String url, CallbackContext callbackContext) { boolean hostNameResolved = false; InetAddress address = null; try { // 'host' can be a ddd.ddd.ddd.ddd or named URL, so doesn't always resolve address = InetAddress.getByName(url); hostNameResolved = true; } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (hostNameResolved) callbackContext.success(address.getHostAddress()); else callbackContext.error("Error resolving host name: " + url); } }); return true; } else if ("resolveHostNameWithUserDefinedCallbackString".equals(action)) { final String url = args.getString(0); final String userString = args.getString(1); // Run the UDP transmission on its own thread (it fails on some Android environments if run on the same thread) cordova.getThreadPool().execute(new Runnable() { public void run() { this.resolveHostNameWithUserDefinedCallbackString(url, userString, callbackContext); } private void resolveHostNameWithUserDefinedCallbackString(String url, String userString, CallbackContext callbackContext) { boolean hostNameResolved = false; InetAddress address = null; try { // 'host' can be a ddd.ddd.ddd.ddd or named URL, so doesn't always resolve address = InetAddress.getByName(url); hostNameResolved = true; } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (hostNameResolved) callbackContext.success(address.getHostAddress() + "|" + userString); else callbackContext.error("|" + userString); } }); return true; } return false; }
From source file:org.openhab.binding.hue.internal.tools.SsdpDiscovery.java
/** * Broadcasts a SSDP discovery message into the network to find provided * services./*from w ww.j ava 2 s . c o m*/ * * @return The Socket the answers will arrive at. * @throws UnknownHostException * @throws IOException * @throws SocketException * @throws UnsupportedEncodingException */ private MulticastSocket sendDiscoveryBroacast() throws UnknownHostException, IOException, SocketException, UnsupportedEncodingException { InetAddress multicastAddress = InetAddress.getByName("239.255.255.250"); final int port = 1900; MulticastSocket socket = new MulticastSocket(port); socket.setReuseAddress(true); socket.setSoTimeout(130000); socket.joinGroup(multicastAddress); byte[] requestMessage = DISCOVER_MESSAGE.getBytes("UTF-8"); DatagramPacket datagramPacket = new DatagramPacket(requestMessage, requestMessage.length, multicastAddress, port); socket.send(datagramPacket); return socket; }
From source file:fi.tut.fast.MulticastProducer.java
public void process(Exchange exchange) throws Exception { InputStream is = exchange.getIn().getBody(InputStream.class); byte[] buf = IOUtils.toByteArray(is); DatagramPacket out = new DatagramPacket(buf, buf.length, endpoint.getMulticastGroup(), endpoint.getMulticastAddress().getPort()); try {/*from w w w . j a v a 2 s .c o m*/ s.send(out); LOG.debug("Packet Sent..."); StringWriter writer = new StringWriter(); IOUtils.write(buf, writer); LOG.debug(writer.toString()); } catch (SocketException ex) { LOG.error("Socket Closed before DatagramPacket could be sent.", ex); } catch (IOException ex) { LOG.error("Socket Closed before DatagramPacket could be sent.", ex); } }
From source file:com.ionicsdk.discovery.Discovery.java
public void doIdentify(final JSONObject opts, final CallbackContext callbackContext) { new AsyncTask<Integer, Void, Void>() { @Override/* w w w . j a v a 2 s . c om*/ 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:org.shept.util.Monitor.java
/** * Send a simple 'Keep Alive' Datagram to the receiver *///w w w . jav a 2s . c o m public Boolean keepAlive() { try { InetAddress adr = InetAddress.getByName(hostname); byte[] data = sendMsg.getBytes(); DatagramSocket socket = new DatagramSocket(); DatagramPacket pack = new DatagramPacket(data, data.length, adr, hostPort); socket.setSoTimeout(msecsSendTimeout); socket.send(pack); socket.close(); return true; } catch (Exception ex) { return false; } }