List of usage examples for java.net DatagramSocket DatagramSocket
public DatagramSocket() throws SocketException
From source file:org.apache.axis2.transport.udp.UDPSender.java
@Override public void sendMessage(MessageContext msgContext, String targetEPR, OutTransportInfo outTransportInfo) throws AxisFault { UDPOutTransportInfo udpOutInfo;//from w ww .ja v a 2s . c o m if ((targetEPR == null) && (outTransportInfo != null)) { // this can happen only at the server side and send the message using back chanel udpOutInfo = (UDPOutTransportInfo) outTransportInfo; } else { udpOutInfo = new UDPOutTransportInfo(targetEPR); } MessageFormatter messageFormatter = TransportUtils.getMessageFormatter(msgContext); OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext); format.setContentType(udpOutInfo.getContentType()); byte[] payload = messageFormatter.getBytes(msgContext, format); try { DatagramSocket socket = new DatagramSocket(); if (log.isDebugEnabled()) { log.debug("Sending " + payload.length + " bytes to " + udpOutInfo.getAddress()); } try { socket.send(new DatagramPacket(payload, payload.length, udpOutInfo.getAddress())); if (!msgContext.getOptions().isUseSeparateListener() && !msgContext.isServerSide()) { waitForReply(msgContext, socket, udpOutInfo.getContentType()); } } finally { socket.close(); } } catch (IOException ex) { throw new AxisFault("Unable to send packet", ex); } }
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 w w w . ja va2s . 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: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); }//www. 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.springframework.integration.syslog.inbound.SyslogReceivingChannelAdapterTests.java
@Test public void testUdp() throws Exception { SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean( SyslogReceivingChannelAdapterFactoryBean.Protocol.udp); int port = SocketUtils.findAvailableUdpSocket(1514); factory.setPort(port);//from w w w. ja v a 2 s . c o m PollableChannel outputChannel = new QueueChannel(); factory.setOutputChannel(outputChannel); factory.setBeanFactory(mock(BeanFactory.class)); factory.afterPropertiesSet(); factory.start(); UdpSyslogReceivingChannelAdapter adapter = (UdpSyslogReceivingChannelAdapter) factory.getObject(); Thread.sleep(1000); byte[] buf = "<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE".getBytes("UTF-8"); DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost", port)); DatagramSocket socket = new DatagramSocket(); socket.send(packet); socket.close(); Message<?> message = outputChannel.receive(10000); assertNotNull(message); assertEquals("WEBERN", message.getHeaders().get("syslog_HOST")); adapter.stop(); }
From source file:org.apache.hadoop.metrics2.ovis.OvisSink.java
@Override public void init(SubsetConfiguration conf) { ldmsSamplerPort = conf.getInt("port", DEFAULT_PORT); hostname = conf.getString("host", DEFAULT_HOST); daemonName = conf.getString("daemon", "unknown"); try {/*w ww .j av a2s . c o m*/ ldmsSamplerAddr = InetAddress.getByName(hostname); socket = new DatagramSocket(); } catch (Exception e) { throw new MetricsException("OvisSink: Failed to new " + "DatagramSocket: " + e.getMessage()); } }
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:com.navercorp.pinpoint.collector.receiver.thrift.udp.UDPReceiverTest.java
@Test public void socketBufferSize() throws SocketException { DatagramSocket datagramSocket = new DatagramSocket(); int receiveBufferSize = datagramSocket.getReceiveBufferSize(); logger.debug("{}", receiveBufferSize); datagramSocket.setReceiveBufferSize(64 * 1024 * 10); logger.debug("{}", datagramSocket.getReceiveBufferSize()); datagramSocket.close();// ww w .j a va 2 s .co m }
From source file:uk.me.sa.lightswitch.android.net.RequestMessage.java
private void sendMessageTo(byte[] message, String node) throws RemoteMessageException { try {/*from w ww . j a va 2 s . co m*/ DatagramSocket s = new DatagramSocket(); try { InetAddress[] addresses = InetAddress.getAllByName(node); List<IOException> failed = new ArrayList<IOException>(addresses.length); for (InetAddress address : addresses) { log.trace("Sending {} bytes to {}", message.length, address); try { s.send(new DatagramPacket(message, message.length, new InetSocketAddress(address, SERVICE))); } catch (IOException e) { log.warn("Error sending datagram packet", e); failed.add(e); } } if (addresses.length == 0) { log.error("No hosts to send to"); throw new RemoteMessageException(new IllegalArgumentException("No hosts to send to")); } else if (failed.size() == addresses.length) { log.error("Error sending all datagram packets"); throw new RemoteMessageException(failed.get(0)); } else if (!failed.isEmpty()) { log.error("Error sending some (but not all) datagram packets"); } } catch (UnknownHostException e) { log.error("Error resolving hostname", e); throw new RemoteMessageException(e); } catch (RuntimeException e) { log.error("Error sending request message", e); throw new RemoteMessageException(e); } finally { s.close(); } } catch (SocketException e) { log.error("Error creating socket", e); throw new RemoteMessageException(e); } }
From source file:org.shept.util.Monitor.java
/** * Send a simple 'Keep Alive' Datagram to the receiver *///from ww w .j a va 2 s . co 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; } }
From source file:org.midonet.util.netty.TestServerFrontEndUPD.java
private DatagramPacket sendMSG(byte[] msg, int port) throws Exception { DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("localhost"); DatagramPacket sendPacket = new DatagramPacket(msg, msg.length, IPAddress, port); clientSocket.send(sendPacket);//from w w w. j a va 2 s . c om clientSocket.close(); return sendPacket; }