List of usage examples for java.net DatagramSocket DatagramSocket
public DatagramSocket(int port) throws SocketException
From source file:MulticastClient.java
public QuoteServerThread(String name) throws IOException { super(name); socket = new DatagramSocket(4445); try {/*from w w w.ja v a 2s .c o m*/ in = new BufferedReader(new FileReader("one-liners.txt")); } catch (FileNotFoundException e) { System.err.println("Could not open quote file. Serving time instead."); } }
From source file:Networking.Networking.java
/** * Constructs a new {@see #Networking} object. Sets {@see #state} to * {@see Networking.NetworkState#NOT_CONNECTED}, initializes {@see #udpInData} * as array of 512 bytes. Sets {@see #playerPortUDP} to value defined in * {@see edu.cvut.vorobvla.bap.BapPorts#PLAYER_PORT} and initializes * {@see udpSocket} with this value as constructor parameter (a port to * bind with this socket). If initialization fails * ({@code SocketException} occurs) increments {@see #playerPortUDP} and * attempts to initialize {@see udpSocket} with parameter {@see #playerPortUDP}. * Proceeds like this until initialization succeeds or until {@see #playerPortUDP} * reaches {@see edu.cvut.vorobvla.bap.BapPorts#PLAYER_PORT}{@code + } * {@see edu.cvut.vorobvla.bap.BapPorts#PLAYER_PORT_RANGE}{@code - 1}. * Initializes {@see networkListener} as an anonymous {@code Thread} child * with overridden {@code run()} method. * <p> The {@code run()} method//from www .j a v a2 s. c o m * the greatest part of the network protocol (waits for * {@see edu.cvut.vorobvla.bap.BapMessages#MSG_CALL_FOR_PLAYERS}, processes it * and calls {@see establishConnectionWithModerator} and {@see recvOpts}). * <p>Constructor of {@see #Networking} proceeds with setting {@see #gameListener} * to {@code null}, {@see #broadcastLatestTimestamp} to {@code 0} and * initializing {@see #parser}. * * @throws SocketException if all attempts to initialize {@see udpSocket} * were unsuccessful. */ private Networking() throws SocketException { state = NetworkState.NOT_CONNECTED; this.playerPortUDP = BapPorts.PLAYER_PORT; // identity = Player.getInstance().getName(); udpInData = new byte[512]; while (udpSocket == null) {//may be bug try { udpSocket = new DatagramSocket(playerPortUDP); } catch (SocketException ex) { if (playerPortUDP < BapPorts.PLAYER_PORT + BapPorts.PLAYER_PORT_RANGE) { Logger.getLogger(Networking.class.getName()).log(Level.INFO, "bad UDP port " + playerPortUDP + ". trying another...", "bad UDP port " + playerPortUDP + ". trying another..."); playerPortUDP++; } else { throw new SocketException("no suttable UDP port"); //Logger.getLogger(Networking.class.getName()).log(Level.SEVERE, null, "no suttable UDP port"); //break; } } } networkListener = new Thread() { @Override public void run() { try { // System.out.println("Start listening to UDP broadcast on" // + udpSocket.getLocalSocketAddress().toString()); DatagramPacket initMsgFromModerator = recvUDP(); String msg = new String(initMsgFromModerator.getData()); if (!msg.split(":")[0].matches(BapMessages.MSG_CALL_FOR_PLAYERS)) { System.err.println("wrong message. got '" + msg + "' while '" + BapMessages.MSG_CALL_FOR_PLAYERS + "' expexted"); return; } System.out.println("RECEVED: " + msg); //get the moderator's IP from the pachage and the port that is listen by it from the message establishConnectionWithModerator(initMsgFromModerator.getAddress(), Integer.parseInt(msg.split(BapMessages.FIELD_DELIM)[1].replaceAll("\\D", ""))); recvOpts(); } catch (IOException ex) { Logger.getLogger(Networking.class.getName()).log(Level.SEVERE, null, ex); System.err.println("exception while establishing connection"); } } }; gameListener = null; parser = new JSONParser(); broadcastLatestTimestamp = 0; // establishConnectionWithModerator(); }
From source file:IntergrationTest.OCSPIntegrationTest.java
/** * Method to test a port is available.// w w w . java2s .c om * * @param port * * @return */ private boolean available(int port) { if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) { 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.google.appinventor.components.runtime.BlockyTalky.java
/** * Creates a new BlockyTalky component.//from w ww .jav a2 s.c o m */ public BlockyTalky(ComponentContainer container) { super(container.$form()); androidUIHandler = new Handler(); localBTs = new ConcurrentHashMap<String, LocalBTData>(); headers = new HashMap<String, String>() { { put("Sec-WebSocket-Protocol", "echo-protocol"); } }; handler = new Handler(); announcerHandler = new Handler(); Log.d(LOG_TAG, "Done with BlockyTalky constructor."); String addr = getIPAddress(true); if (addr.equals("")) { addr = getIPAddress(false); } try { mContext = container.$context(); InetAddress ip = InetAddress.getByName(addr); //Android ip InetAddress bip = InetAddress.getByName(MULTICAST_ADDRESS); ds = new DatagramSocket(UNICAST_PORT); //ds.setReuseAddress(true); broadcastSocket = new MulticastSocket(MULTICAST_PORT); broadcastSocket.joinGroup(bip); broadcastSocket.setBroadcast(true); MessageListener listener = new MessageListener(); Thread listenerThread = new Thread(listener); listenerThread.start(); BroadcastListener broadcastListener = new BroadcastListener(); Thread broadcastThread = new Thread(broadcastListener); broadcastThread.start(); aquireMulticastLock(); BroadcastAnnouncer announcer = new BroadcastAnnouncer(); Thread announcerThread = new Thread(announcer); announcerThread.start(); } catch (SocketException e) { Log.d(LOG_TAG, "Caught SocketException while trying to initialize BlockyTalky messaging: " + e.getMessage()); e.printStackTrace(); } catch (UnknownHostException e) { Log.d(LOG_TAG, "Caught UnknownHostException while trying to reach Blockytalky messaging router: " + e.getMessage()); } catch (Exception e) { Log.d(LOG_TAG, "Exception while initializing BlockyTalky messaging: " + e); e.printStackTrace(); } connectToMessagingRouter(); }
From source file:org.rifidi.emulator.reader.alien.heartbeat.HeartbeatController.java
/** * Send out a heartbeat//from w ww. j av a 2 s . c o m */ private void broadcast() { String retString = "<Alien-RFID-Reader-Heartbeat>\n" + " <ReaderName>Alien RFID Reader</ReaderName>\n" + " <ReaderType>Alien RFID Tag Reader, Model: ALR-9800(Four Antenna / Multi-Protocol / 915 Mhz)" + "</ReaderType>\n" + " <IPAddress>" + asr.getCommandIP() + "</IPAddress>\n" + " <CommandPort>" + asr.getCommandPort() + "</CommandPort>\n" + " <HeartbeatTime>" + this.timeInMs / 1000 + "</HeartbeatTime>\n" + " <MACAddress>00:00:00:00:00:00</MACAddress>\n" + "</Alien-RFID-Reader-Heartbeat>\n"; try { logger.debug("Attempting to send heartbeat..."); DatagramSocket sock = new DatagramSocket(bindingPort); InetAddress ia = InetAddress.getByName(broadcastAddr); sock.setBroadcast(true); DatagramPacket p = new DatagramPacket(retString.getBytes(), retString.getBytes().length, ia, broadcastPort); sock.send(p); sock.disconnect(); sock.close(); } catch (SocketException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.parakoopa.udphp.mediator.Mediator.java
public Mediator() { try {//w w w . j a v a 2 s. c o 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("UDPHP 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("-> UDP: 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("-> TCP: 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(); } catch (IOException ex) { //Print all exceptions. ex.printStackTrace(); } }
From source file:org.avineas.fins.gw.Gateway.java
/** * Set the local UDP port of this gateway. * //from w w w .jav a 2s .c o m * @param port The UDP port number * @throws SocketException */ public synchronized void setPort(int port) throws SocketException { if (channel != null) channel.close(); channel = new DatagramSocket(port); }
From source file:vitro.vgw.wsiadapter.WSIAdapterCoap.java
/** * WSIAdapter interface/*from w ww. j a v a 2 s . c o m*/ */ public List<Node> getAvailableNodeList() throws WSIAdapterException { logger.info("Getting available nodes..."); nodesList = new ArrayList<Node>(); List<String> wsnProxyList = new LinkedList<String>(); wsnProxyList.add(Network.WLAB_OFFICE_PROXY_ADDRESS); wsnProxyList.add(Network.WLAB_LAB_PROXY_ADDRESS); DatagramSocket serverSocket = null; DatagramSocket clientSocket = null; String cmdString = "route"; for (int i = 0; i < wsnProxyList.size(); i++) { try { serverSocket = new DatagramSocket(Constants.UDPSHELL_VGW_PORT); String hostProxyString = wsnProxyList.get(i); InetAddress hostProxy = InetAddress.getByName(hostProxyString); clientSocket = new DatagramSocket(); byte[] bufCmd = new byte[10]; bufCmd = cmdString.getBytes(); DatagramPacket outcomingPacket = new DatagramPacket(bufCmd, bufCmd.length, hostProxy, Constants.PROXY_UDPFORWARDER_PORT); clientSocket.send(outcomingPacket); boolean otherPackets = false; serverSocket.setSoTimeout(Constants.PROXY_RESPONSE_TIMEOUT); logger.info("Quering " + hostProxyString); try { byte[] bufAck = new byte[10]; DatagramPacket ackPacket = new DatagramPacket(bufAck, bufAck.length); serverSocket.receive(ackPacket); String ackString = new String(ackPacket.getData()).trim(); if (ackString.equals("ack")) { otherPackets = true; } } catch (SocketTimeoutException e) { logger.warn(e.getMessage()); } serverSocket.setSoTimeout(0); while (otherPackets) { try { byte[] bufIncoming = new byte[1000]; DatagramPacket incomingPacket = new DatagramPacket(bufIncoming, bufIncoming.length); serverSocket.receive(incomingPacket); String currentNodeIP = new String(incomingPacket.getData()).trim(); if (!currentNodeIP.equals("end")) { logger.info("Node: " + currentNodeIP); nodesList.add(new Node(currentNodeIP)); } else { otherPackets = false; logger.info("No other nodes from " + hostProxyString); } } catch (IOException e) { logger.error(e.getMessage()); } } } catch (UnknownHostException e) { logger.warn(e.getMessage() + " is not reachable."); } catch (SocketException e) { logger.error(e.getMessage()); } catch (IOException e) { logger.error(e.getMessage()); } finally { if (serverSocket != null) { serverSocket.close(); } if (clientSocket != null) { clientSocket.close(); } } } return nodesList; }
From source file:org.apache.tajo.rpc.NettyServerBase.java
private static boolean available(int port) throws IOException { if (port < 1024 || port > 65535) { throw new IllegalArgumentException("Port Number Out of Bound: " + port); }/*from w ww . j a v a2 s .com*/ 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) { return false; } finally { if (ss != null) { ss.close(); } if (ds != null) { ds.close(); } } }
From source file:org.eclipse.smarthome.binding.wemo.discovery.WemoDiscoveryService.java
public void sendWemoDiscoveryMessage() { logger.debug("wemoDiscovery() is called!"); try {//from w w w .j a v a2 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); } }