List of usage examples for java.net DatagramSocket DatagramSocket
public DatagramSocket(int port) throws SocketException
From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.transport.TransportUtils.java
private static boolean checkIfPortAvailable(int port) { ServerSocket tcpSocket = null; DatagramSocket udpSocket = null; try {//from w ww .j a v a2s . c o m tcpSocket = new ServerSocket(port); tcpSocket.setReuseAddress(true); udpSocket = new DatagramSocket(port); udpSocket.setReuseAddress(true); return true; } catch (IOException ex) { // denotes the port is in use } finally { if (tcpSocket != null) { try { tcpSocket.close(); } catch (IOException e) { /* not to be thrown */ } } if (udpSocket != null) { udpSocket.close(); } } return false; }
From source file:org.openacs.HostsBean.java
public void RequestConnectionUDP(String url, String user, String pass) throws Exception { DatagramSocket s = new DatagramSocket(null); s.setReuseAddress(true);//from w w w.j a va 2 s . c o m s.bind(new InetSocketAddress(Application.getSTUNport())); String ts = Long.toString(Calendar.getInstance().getTimeInMillis()); String id = ts; Random rnd = new Random(); byte[] nonceArray = new byte[16]; rnd.nextBytes(nonceArray); String cn = cvtHex.cvtHex(nonceArray); url = url.substring(6); String[] u = url.split(":"); SecretKeySpec signingKey = new SecretKeySpec(pass.getBytes(), HMAC_SHA1_ALGORITHM); Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); String data = ts + id + user + cn; byte[] rawHmac = mac.doFinal(data.getBytes()); String signature = cvtHex.cvtHex(rawHmac); String req = "GET http://" + url + "?ts=" + ts + "&id=" + id + "&un=" + user + "&cn=" + cn + "&sig=" + signature + " HTTP/1.1\r\n\r\n"; byte[] breq = req.getBytes(); DatagramPacket packet = new DatagramPacket(breq, breq.length); packet.setAddress(InetAddress.getByName(u[0])); packet.setPort(Integer.parseInt(u[1])); s.send(packet); }
From source file:org.exoplatform.addons.es.integration.BaseIntegrationTest.java
/** * Get a random available port//from ww w. j av a 2s .c o m * @return * @throws IOException */ private static int getAvailablePort() throws IOException { ServerSocket ss = null; DatagramSocket ds = null; try { ss = new ServerSocket(0); ss.setReuseAddress(true); ds = new DatagramSocket(0); ds.setReuseAddress(true); return ss.getLocalPort(); } finally { if (ds != null) { ds.close(); } if (ss != null) { try { ss.close(); } catch (IOException e) { /* should not be thrown */ } } } }
From source file:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.uplink.UplinkReceiver.java
public void init() throws SocketException { this.setName(this.getClass().getSimpleName()); this.sock = new DatagramSocket(null); this.sock.setReuseAddress(true); this.sock.bind(new InetSocketAddress(this.uplinkUdpPort)); this.start(); }
From source file:org.jumpmind.util.AppUtils.java
/** * Checks to see if a specific port is available. * * @param port//from ww w .ja v a2 s. c o m * the port to check for availability */ public static boolean isPortAvailable(int port) { if (port < 1 || port > 65535) { throw new IllegalArgumentException("Invalid start port: " + port); } ServerSocket ss = null; DatagramSocket ds = null; try { ss = new ServerSocket(port); ss.setReuseAddress(true); ds = new DatagramSocket(port); ds.setReuseAddress(true); return true; } catch (IOException e) { } finally { if (ds != null) { ds.close(); } if (ss != null) { try { ss.close(); } catch (IOException e) { /* should not be thrown */ } } } return false; }
From source file:com.clearspring.metriccatcher.Loader.java
/** * Load properties, build a MetricCatcher, start catching * * @param propertiesFile The config file * @throws IOException if the properties file cannot be read *///from w ww. j av a2s . com public Loader(File propertiesFile) throws IOException { logger.info("Starting metriccatcher"); logger.info("Loading configuration from: " + propertiesFile.getAbsolutePath()); Properties properties = new Properties(); try { properties.load(new FileReader(propertiesFile)); for (Object key : properties.keySet()) { // copy properties into system properties System.setProperty((String) key, (String) properties.get(key)); } } catch (IOException e) { logger.error("error reading properties file: " + e); System.exit(1); } int reportingInterval = 60; String intervalProperty = properties.getProperty(METRICCATCHER_INTERVAL); if (intervalProperty != null) { try { reportingInterval = Integer.parseInt(intervalProperty); } catch (NumberFormatException e) { logger.warn("Couldn't parse " + METRICCATCHER_INTERVAL + " setting", e); } } boolean disableJvmMetrics = false; String disableJvmProperty = properties.getProperty(METRICCATCHER_DISABLE_JVM_METRICS); if (disableJvmProperty != null) { disableJvmMetrics = BooleanUtils.toBoolean(disableJvmProperty); if (disableJvmMetrics) { logger.info("Disabling JVM metric reporting"); } } boolean reportingEnabled = false; // Start a Ganglia reporter if specified in the config String gangliaHost = properties.getProperty(METRICCATCHER_GANGLIA_HOST); String gangliaPort = properties.getProperty(METRICCATCHER_GANGLIA_PORT); if (gangliaHost != null && gangliaPort != null) { logger.info("Creating Ganglia reporter pointed at " + gangliaHost + ":" + gangliaPort); GangliaReporter gangliaReporter = new GangliaReporter(gangliaHost, Integer.parseInt(gangliaPort)); gangliaReporter.printVMMetrics = !disableJvmMetrics; gangliaReporter.start(reportingInterval, TimeUnit.SECONDS); reportingEnabled = true; } // Start a Graphite reporter if specified in the config String graphiteHost = properties.getProperty(METRICCATCHER_GRAPHITE_HOST); String graphitePort = properties.getProperty(METRICCATCHER_GRAPHITE_PORT); if (graphiteHost != null && graphitePort != null) { String graphitePrefix = properties.getProperty(METRICCATCHER_GRAPHITE_PREFIX); if (graphitePrefix == null) { graphitePrefix = InetAddress.getLocalHost().getHostName(); } logger.info("Creating Graphite reporter pointed at " + graphiteHost + ":" + graphitePort + " with prefix '" + graphitePrefix + "'"); GraphiteReporter graphiteReporter = new GraphiteReporter(graphiteHost, Integer.parseInt(graphitePort), StringUtils.trimToNull(graphitePrefix)); graphiteReporter.printVMMetrics = !disableJvmMetrics; graphiteReporter.start(reportingInterval, TimeUnit.SECONDS); reportingEnabled = true; } String reporterConfigFile = properties.getProperty(METRICCATCHER_REPORTER_CONFIG); if (reporterConfigFile != null) { logger.info("Trying to load reporterConfig from file: {}", reporterConfigFile); try { ReporterConfig.loadFromFileAndValidate(reporterConfigFile).enableAll(); } catch (Exception e) { logger.error("Failed to load metrics-reporter-config, metric sinks will not be activated", e); } reportingEnabled = true; } if (!reportingEnabled) { logger.error("No reporters enabled. MetricCatcher can not do it's job"); throw new RuntimeException("No reporters enabled"); } int maxMetrics = Integer.parseInt(properties.getProperty(METRICCATCHER_MAX_METRICS, "500")); logger.info("Max metrics: " + maxMetrics); Map<String, Metric> lruMap = new LRUMap<String, Metric>(10, maxMetrics); int port = Integer.parseInt(properties.getProperty(METRICCATCHER_UDP_PORT, "1420")); logger.info("Listening on UDP port " + port); DatagramSocket socket = new DatagramSocket(port); metricCatcher = new MetricCatcher(socket, lruMap); metricCatcher.start(); // Register a shutdown hook and wait for termination Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { shutdown(); }; }); }
From source file:org.parakoopa.gmnetgate.punch.Mediator.java
public Mediator() { try {//from ww w .ja v a 2 s . co m //Set up some local variables server = new ServerSocket(port); server_udp = new DatagramSocket(port); serverMap = new HashMap(); clientMap = new HashMap(); final Mediator me = this; Mediator.log("GMnet GATE.PUNCH STARTED", false); Mediator.log("Starting UDP and TCP servers on port " + port, false); //Start two new threads for the servers, just to be on the safe side. new Thread() { @Override //START UDP SERVER public void run() { Mediator.log("Loaded UDP Listener", true); //When packet is processed: Continue with next packet while (true) { try { //Create incoming packet and wait for it. DatagramPacket packet = new DatagramPacket(receiveData, receiveData.length); server_udp.receive(packet); //When a packet arrivied: Deal with it. UDPPacket packetHandler = new UDPPacket(me, packet, server_udp); //This was once also a seperate thread, that's why the method is called run. //annother thread is not needed though. //it is propably even more efficient to just swap the packet out instead of //creating a new class above. Do what you want :) packetHandler.run(); } catch (IOException ex) { //Print all exceptions. ex.printStackTrace(); } } } }.start(); new Thread() { @Override //START TCP SERVER public void run() { Mediator.log("Loaded TCP Listener", true); //When connection thread is created: Wait for next connection while (true) { try { //Wait for connection Socket client = server.accept(); //When connection is opened: Start thread that handles it. TCPConnection connectionHandler = new TCPConnection(me, client, server); new Thread(connectionHandler).start(); } catch (IOException ex) { //Print all exceptions. ex.printStackTrace(); } } } }.start(); if (Mediator.dbg_servers) { for (int i = 0; i < 50; i++) { Server serverObj = this.getServer(UUID.randomUUID().toString()); serverObj.setData1(UUID.randomUUID().toString()); serverObj.setData2(UUID.randomUUID().toString()); serverObj.setData3(UUID.randomUUID().toString()); serverObj.setData4(UUID.randomUUID().toString()); serverObj.setData5(UUID.randomUUID().toString()); serverObj.setData6(UUID.randomUUID().toString()); serverObj.setData7(UUID.randomUUID().toString()); serverObj.setData8(UUID.randomUUID().toString()); } } } catch (IOException ex) { //Print all exceptions. ex.printStackTrace(); } }
From source file:org.codice.alliance.test.itests.VideoTest.java
private void waitForUdpStreamMonitorStart() { expect("The UDP stream monitor to start on port " + udpPort.getPort()).within(5, TimeUnit.SECONDS) .until(() -> {/* ww w . j a v a 2 s . com*/ try (DatagramSocket socket = new DatagramSocket(udpPortNum)) { return false; } catch (SocketException e) { return true; } }); }
From source file:udpserver.UDPui.java
private void receiveUDP() { countSeparate = new ArrayList<>(); background = new Runnable() { public void run() { try { serverSocket = new DatagramSocket(9876); } catch (SocketException ex) { Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex); }/*from w ww . j a va 2 s.co m*/ // while (true) { // byte[] receiveData = new byte[1024]; // DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); //<editor-fold defaultstate="collapsed" desc="Start timer after receive a packet"> // try { // serverSocket.receive(receivePacket); // series.clear(); // valuePane.setText(""); available = true; // System.out.println(available); // } catch (IOException ex) { // Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex); // } // Timer timer = new Timer(); // timer.schedule(new TimerTask() { // @Override // public void run() { // available = false; // System.out.println("Finish Timer"); // } // }, 1 * 1000); //</editor-fold> // if (!new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()).equals("")) { // int count = 1; // while (available) { while (true) { try { byte[] receiveData = new byte[total_byte]; byte[] sendData = new byte[32]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String word = receivePacket.getAddress().getHostAddress(); System.out.println(word); String message = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()); boolean looprun = true; // System.out.println(message); while (looprun) { Integer countt = counting.get(word); if (message.contains("&")) { message = message.substring(message.indexOf("&") + 1); // count++; // Integer countt = counting.get(word); if (countt == null) { counting.put(word, 1); } else { counting.put(word, countt + 1); } // System.out.println(count + ":" + message); } else { if (countt == null) { counting.put(word, 1); } else { counting.put(word, countt + 1); } System.out.println(counting.get(word)); looprun = false; } } if (message.contains("start")) { if (counting.get(word) != null) { counting.remove(word); } } else if (message.contains("end")) { message = message.substring(message.indexOf("end") + 3); // valuePane.setCaretPosition(valuePane.getDocument().getLength()); //send back to mobile InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); // String capitalizedSentence = count + ""; String capitalizedSentence = counting.get(word) + ""; sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss") .format(Calendar.getInstance().getTime()); String content = IPAddress.getCanonicalHostName() + "," + timeStamp + "," + (counting.get(word) - 1) + "," + message; saveFile(content); //end send back to mobile // System.out.println(counting.get(word)); // count = 1; counting.remove(word); // break; } else if (available) { //<editor-fold defaultstate="collapsed" desc="check hasmap key"> // if (hm.size() > 0 && hm.containsKey(serverSocket.getInetAddress().getHostAddress())) { // hm.put(foundKey, new Integer(((int) hm.get(foundKey)) + 1)); // hm.put(serverSocket.getInetAddress().getHostAddress(), new Integer(((int) hm.get(serverSocket.getInetAddress().getHostAddress())) + 1)); // } else { // hm.put(serverSocket.getInetAddress().getHostAddress(), 1); // hm.entrySet().add(new Map<String, Integer>.Entry<String, Integer>()); // } //</editor-fold> // series.add(count, Double.parseDouble(message)); // valuePane.setText(valuePane.getText().toString() + count + ":" + message + "\n"); // valuePane.setCaretPosition(valuePane.getDocument().getLength()); // count++; } } catch (IOException ex) { Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex); valuePane.setText(valuePane.getText().toString() + "IOException" + "\n"); } } // valuePane.setText(valuePane.getText().toString() + "Out of while loop" + "\n"); // } // } } private void saveFile(String content) { try { File desktop = new File(System.getProperty("user.home"), "Desktop"); File file = new File(desktop.getAbsoluteFile() + "/udp.csv"); if (!file.exists()) { file.createNewFile(); } FileOutputStream fop = new FileOutputStream(file, true); fop.write((content + "\n").getBytes()); fop.flush(); fop.close(); // String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(Calendar.getInstance().getTime()); // valuePane.setText(valuePane.getText().toString() + timeStamp + "\n"); } catch (IOException ex) { Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex); String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss") .format(Calendar.getInstance().getTime()); valuePane.setText(valuePane.getText().toString() + timeStamp + "\n"); } } }; backgroundProcess = new Thread(background); }
From source file:com.adito.agent.client.tunneling.LocalTunnelServer.java
/** * Start listening for incoming connections to this listener. When * successful, this method will return immediately. //w ww . j a v a 2 s . c om * @throws IOException */ public void start() throws IOException { if (stopping) { throw new IOException("Local forwarding is currently stopping."); } if (isListening()) { throw new IOException("Local forwarding is already listening."); } dataLastTransferred = System.currentTimeMillis(); // #ifdef DEBUG if (listeningSocketConfiguration.isPermanent()) { log.info("Starting permanent listening socket on port " + listeningSocketConfiguration.getSourcePort()); //$NON-NLS-1$ } else { log.info("Starting temporary listening socket on port " + listeningSocketConfiguration.getSourcePort()); //$NON-NLS-1$ } // #endif /* Bind server socket */ if (listeningSocketConfiguration.getTransport().equals(TunnelConfiguration.UDP_TUNNEL)) { // #ifdef DEBUG log.info("Creating UDP server socket on port " + listeningSocketConfiguration.getSourcePort()); //$NON-NLS-1$ // #endif datagramSocket = new DatagramSocket(listeningSocketConfiguration.getSourcePort()); } else { // #ifdef DEBUG if (listeningSocketConfiguration.getSourcePort() == 0) log.info("Creating TCP server socket random port"); //$NON-NLS-1$ else log.info("Creating TCP server socket on port " + listeningSocketConfiguration.getSourcePort()); //$NON-NLS-1$ // #endif /* If the specified port is 0 then ServerSocket will select the * next free port. We then need to store the port actually used * back into the configuration so application launching can * work. */ boolean resetPort = listeningSocketConfiguration.getSourcePort() == 0; server = new ServerSocket(listeningSocketConfiguration.getSourcePort(), 50, InetAddress.getByName(getAddressToBind())); if (resetPort) { // #ifdef DEBUG log.info("Chosen port " + server.getLocalPort()); //$NON-NLS-1$ // #endif listeningSocketConfiguration.setSourcePort(server.getLocalPort()); } } fireLocalTunnelServerStarted(); thread = new Thread(new Runnable() { public void run() { tunnelTCP(); } }); thread.setDaemon(true); thread.setName("SocketListener " + getAddressToBind() + ":" //$NON-NLS-1$//$NON-NLS-2$ + String.valueOf(listeningSocketConfiguration.getSourcePort())); thread.start(); }