List of usage examples for java.net DatagramSocket DatagramSocket
public DatagramSocket() throws SocketException
From source file:org.lwes.emitter.UnicastEventEmitter.java
/** * Initializes the emitter./*from www . jav a 2 s . com*/ */ public void initialize() throws IOException { try { factory.initialize(); socket = new DatagramSocket(); socket.setReuseAddress(true); } catch (IOException ie) { throw ie; } catch (Exception e) { log.error("Unable to initialize UnicastEventEmitter", e); } }
From source file:net.pms.network.UPNPHelper.java
/** * Send reply.// w w w . ja va 2 s.c om * * @param host the host * @param port the port * @param msg the msg * @throws IOException Signals that an I/O exception has occurred. */ private static void sendReply(String host, int port, String msg) { DatagramSocket datagramSocket = null; try { datagramSocket = new DatagramSocket(); InetAddress inetAddr = InetAddress.getByName(host); DatagramPacket dgmPacket = new DatagramPacket(msg.getBytes(), msg.length(), inetAddr, port); logger.trace( "Sending this reply [" + host + ":" + port + "]: " + StringUtils.replace(msg, CRLF, "<CRLF>")); datagramSocket.send(dgmPacket); } catch (Exception e) { logger.info(e.getMessage()); logger.debug("Error sending reply", e); } finally { if (datagramSocket != null) { datagramSocket.close(); } } }
From source file:com.mendhak.gpslogger.common.OpenGTSClient.java
public void sendRAW(String id, String accountName, SerializableLocation[] locations) throws Exception { for (SerializableLocation loc : locations) { if (Utilities.IsNullOrEmpty(accountName)) { accountName = id;/*from w ww. j av a 2 s . com*/ } String message = accountName + "/" + id + "/" + GPRMCEncode(loc); DatagramSocket socket = new DatagramSocket(); byte[] buffer = message.getBytes(); DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName(server), port); tracer.debug("Sending UDP " + message); socket.send(packet); socket.close(); } }
From source file:org.apache.nifi.processors.standard.TestListenUDP.java
@Test public void testSendingMoreThanQueueSize() throws IOException, InterruptedException { final int maxQueueSize = 3; runner.setProperty(ListenUDP.MAX_MESSAGE_QUEUE_SIZE, String.valueOf(maxQueueSize)); final List<String> messages = getMessages(20); final int expectedQueued = maxQueueSize; final int expectedTransferred = maxQueueSize; run(new DatagramSocket(), messages, expectedQueued, expectedTransferred); runner.assertAllFlowFilesTransferred(ListenUDP.REL_SUCCESS, maxQueueSize); List<MockFlowFile> mockFlowFiles = runner.getFlowFilesForRelationship(ListenUDP.REL_SUCCESS); verifyFlowFiles(mockFlowFiles);/*from ww w . j a va 2s. c o m*/ verifyProvenance(expectedTransferred); }
From source file:com.googlecode.jmxtrans.model.output.TCollectorUDPWriter.java
/** * Setup at start of the writer./* www.j a v a2 s . co m*/ */ @Override public void prepareSender() throws LifecycleException { if (host == null || port == null) { throw new LifecycleException( "Host and port for " + this.getClass().getSimpleName() + " output can't be null"); } try { this.dgSocket = new DatagramSocket(); this.address = new InetSocketAddress(host, port); } catch (SocketException sockExc) { log.error("Failed to create a datagram socket", sockExc); throw new LifecycleException(sockExc); } }
From source file:com.navercorp.pinpoint.profiler.sender.UdpDataSender.java
private DatagramSocket createSocket(String host, int port, int timeout, int sendBufferSize) { try {//from www. j av a 2s . co m final DatagramSocket datagramSocket = new DatagramSocket(); datagramSocket.setSoTimeout(timeout); datagramSocket.setSendBufferSize(sendBufferSize); if (logger.isInfoEnabled()) { final int checkSendBufferSize = datagramSocket.getSendBufferSize(); if (sendBufferSize != checkSendBufferSize) { logger.info("DatagramSocket.setSendBufferSize() error. {}!={}", sendBufferSize, checkSendBufferSize); } } final InetSocketAddress serverAddress = new InetSocketAddress(host, port); datagramSocket.connect(serverAddress); return datagramSocket; } catch (SocketException e) { throw new IllegalStateException("DatagramSocket create fail. Cause" + e.getMessage(), e); } }
From source file:org.nognog.jmatcher.server.JMatcherDaemonTest.java
/** * Test method for {@link org.nognog.jmatcher.JMatcherDaemon#run()}. * /*w w w .java 2 s. co m*/ * @param tcpHandler * @param udpHandler * * @throws Exception */ @SuppressWarnings("unused") @Test public final void testConnect(@Mocked final TCPClientRequestHandler tcpHandler, @Mocked final UDPClientRequestHandler udpHandler) throws Exception { new NonStrictExpectations() { { new TCPClientRequestHandler((JMatcherDaemon) any, (Socket) any, anyInt); result = tcpHandler; new UDPClientRequestHandler((JMatcherDaemon) any, (DatagramSocket) any, (InetSocketAddress) any, (String) any, anyInt); result = udpHandler; } }; final JMatcherDaemon daemon = new JMatcherDaemon(); daemon.init(null); daemon.start(); try (final Socket socket = new Socket("localhost", JMatcher.PORT)) { //$NON-NLS-1$ Thread.sleep(100); new Verifications() { { tcpHandler.run(); times = 1; udpHandler.run(); times = 0; } }; } try (DatagramSocket socket = new DatagramSocket()) { final byte[] buf = "test".getBytes(); //$NON-NLS-1$ final DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost", JMatcher.PORT)); //$NON-NLS-1$ socket.send(packet); Thread.sleep(100); new Verifications() { { tcpHandler.run(); times = 1; udpHandler.run(); times = 1; } }; } daemon.stop(); daemon.destroy(); }
From source file:com.bitbreeds.webrtc.datachannel.DataChannelImpl.java
public DataChannelImpl(PeerConnection parent) throws IOException { logger.info("Initializing {}", this.getClass().getName()); this.dtlsServer = new WebrtcDtlsServer(parent.getKeyStoreInfo()); this.parent = parent; this.channel = new DatagramSocket(); this.channel.setReceiveBufferSize(16000000); this.receiveBufferSize = this.channel.getReceiveBufferSize(); this.channel.setSendBufferSize(16000000); this.sendBufferSize = this.channel.getSendBufferSize(); //this.channel.setReuseAddress(true); this.port = channel.getLocalPort(); this.serverProtocol = new DTLSServerProtocol(new SecureRandom()); this.mode = ConnectionMode.BINDING; /**//from w ww .j a v a 2s . c o m * Print monitoring information */ this.monitor = () -> { while (running && channel.isBound()) { try { Thread.sleep(3000); sctpService.runMonitoring(); } catch (Exception e) { logger.error("Logging error", e); } } }; /** * Create heartbeat message */ this.heartBeat = () -> { while (running && channel.isBound()) { try { Thread.sleep(5000); byte[] beat = sctpService.createHeartBeat(); logger.debug("Sending heartbeat: " + Hex.encodeHexString(beat)); putDataOnWire(beat); } catch (Exception e) { logger.error("HeartBeat error: ", e); } } }; /** * Acknowledge received data */ this.sackSender = () -> { while (running && channel.isBound()) { try { Thread.sleep(1); //sleep to not go ham on cpu logger.trace("Creating sack:"); byte[] beat = sctpService.createSackMessage(); if (beat.length > 0) { logger.trace("Sending sack: " + Hex.encodeHexString(beat)); putDataOnWire(beat); } else { logger.trace("Already on latest sack, no send"); } } catch (Exception e) { logger.error("Sack error: ", e); } } }; /** * Resends non acknowledged sent messages */ this.reSender = () -> { while (running && channel.isBound() && !channel.isClosed()) { try { Thread.sleep(250); List<byte[]> msgs = sctpService.getMessagesForResend(); if (!msgs.isEmpty()) { msgs.forEach(i -> { try { Thread.sleep(1); //Sleep to let others work a bit logger.debug("Resending data: " + Hex.encodeHexString(i)); putDataOnWire(i); } catch (InterruptedException e) { logger.error("Resend error: ", e); } }); } } catch (Exception e) { logger.error("Resend error: ", e); } } }; }
From source file:org.openhab.binding.harmonyhub.discovery.HarmonyHubDiscovery.java
/** * Send broadcast message over all active interfaces * * @param discoverString/* w ww.j av a 2 s. c om*/ * String to be used for the discovery */ private void sendDiscoveryMessage(String discoverString) { DatagramSocket bcSend = null; try { bcSend = new DatagramSocket(); bcSend.setBroadcast(true); byte[] sendData = discoverString.getBytes(); // Broadcast the message over all the network interfaces Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; } for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress[] broadcast = null; if (StringUtils.isNotBlank(optionalHost)) { try { broadcast = new InetAddress[] { InetAddress.getByName(optionalHost) }; } catch (Exception e) { logger.error("Could not use host for hub discovery", e); return; } } else { broadcast = new InetAddress[] { InetAddress.getByName("224.0.0.1"), InetAddress.getByName("255.255.255.255"), interfaceAddress.getBroadcast() }; } for (InetAddress bc : broadcast) { // Send the broadcast package! if (bc != null) { try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, bc, DISCO_PORT); bcSend.send(sendPacket); } catch (IOException e) { logger.debug("IO error during HarmonyHub discovery: {}", e.getMessage()); } catch (Exception e) { logger.debug(e.getMessage(), e); } logger.trace("Request packet sent to: {} Interface: {}", bc.getHostAddress(), networkInterface.getDisplayName()); } } } } } catch (IOException e) { logger.debug("IO error during HarmonyHub discovery: {}", e.getMessage()); } finally { try { if (bcSend != null) { bcSend.close(); } } catch (Exception e) { // Ignore } } }
From source file:org.apache.hadoop.metrics2.sink.ganglia.AbstractGangliaSink.java
public void init(SubsetConfiguration conf) { LOG.debug("Initializing the GangliaSink for Ganglia metrics."); this.conf = conf; // Take the hostname from the DNS class. if (conf.getString("slave.host.name") != null) { hostName = conf.getString("slave.host.name"); } else {// ww w .j a va 2s . c o m try { hostName = DNS.getDefaultHost(conf.getString("dfs.datanode.dns.interface", "default"), conf.getString("dfs.datanode.dns.nameserver", "default")); } catch (UnknownHostException uhe) { LOG.error(uhe); hostName = "UNKNOWN.example.com"; } } // load the gannglia servers from properties metricsServers = Servers.parse(conf.getString(SERVERS_PROPERTY), DEFAULT_PORT); // extract the Ganglia conf per metrics gangliaConfMap = new HashMap<String, GangliaConf>(); loadGangliaConf(GangliaConfType.units); loadGangliaConf(GangliaConfType.tmax); loadGangliaConf(GangliaConfType.dmax); loadGangliaConf(GangliaConfType.slope); try { datagramSocket = new DatagramSocket(); } catch (SocketException se) { LOG.error(se); } // see if sparseMetrics is supported. Default is false supportSparseMetrics = conf.getBoolean(SUPPORT_SPARSE_METRICS_PROPERTY, SUPPORT_SPARSE_METRICS_DEFAULT); }