List of usage examples for java.net DatagramSocket send
public void send(DatagramPacket p) throws IOException
From source file:org.opennms.netmgt.syslogd.SyslogdLoadIT.java
public void doTestSyslogReceiver() throws Exception { final int eventCount = 100; List<Integer> foos = new ArrayList<Integer>(); for (int i = 0; i < eventCount; i++) { int eventNum = Double.valueOf(Math.random() * 10000).intValue(); foos.add(eventNum);//from w w w.j a v a 2 s. c o m } m_eventCounter.setAnticipated(eventCount); String testPduFormat = "2010-08-19 localhost foo%d: load test %d on tty1"; SyslogClient sc = new SyslogClient(null, 10, SyslogClient.LOG_USER, addr("127.0.0.1")); // Test by sending over a java.net socket final DatagramSocket socket = new DatagramSocket(); System.err.println("Starting to send packets"); final long start = System.currentTimeMillis(); for (int i = 0; i < eventCount; i++) { int foo = foos.get(i); DatagramPacket pkt = sc.getPacket(SyslogClient.LOG_DEBUG, String.format(testPduFormat, foo, foo)); socket.send(pkt); } socket.close(); /* // Test by sending over an NIO channel SocketAddress address = new InetSocketAddress(InetAddressUtils.getLocalHostAddress(), SyslogClient.PORT); final DatagramChannel channel = DatagramChannel.open(); final ByteBuffer buffer = ByteBuffer.allocate(SyslogReceiverNioThreadPoolImpl.MAX_PACKET_SIZE); buffer.clear(); System.err.println("Starting to send packets"); final long start = System.currentTimeMillis(); for (int i = 0; i < eventCount; i++) { int foo = foos.get(i); buffer.put(SyslogClient.getPacketPayload(SyslogClient.LOG_USER, null, SyslogClient.LOG_DEBUG, String.format(testPduFormat, foo, foo))); buffer.flip(); channel.send(buffer, address); buffer.clear(); } channel.close(); */ long mid = System.currentTimeMillis(); System.err.println(String.format("Sent %d packets in %d milliseconds", eventCount, mid - start)); m_eventCounter.waitForFinish(30000); long end = System.currentTimeMillis(); System.err.println( String.format("Events expected: %d, events received: %d", eventCount, m_eventCounter.getCount())); final long total = (end - start); final double eventsPerSecond = (eventCount * 1000.0 / total); System.err.println(String.format("total time: %d, wait time: %d, events per second: %8.4f", total, (end - mid), eventsPerSecond)); assertEquals(eventCount, m_eventCounter.getCount()); }
From source file:com.esri.geoevent.test.performance.ClockSync.java
@Override public void run() { DatagramSocket socket = null; try {//from ww w .j a v a2 s. c om byte[] incomingBuffer = new byte[1024]; DatagramPacket packet = new DatagramPacket(incomingBuffer, incomingBuffer.length); ByteBuffer bb = ByteBuffer.allocate(8); DatagramPacket outgoingPacket = new DatagramPacket(bb.array(), 0, 8, null, port); socket = new DatagramSocket(port); socket.setSoTimeout(100); while (isRunning.get()) { try { socket.receive(packet); long now = System.currentTimeMillis(); bb.putLong(now); outgoingPacket.setAddress(packet.getAddress()); outgoingPacket.setPort(packet.getPort()); socket.send(outgoingPacket); bb.clear(); //System.out.println("Sent the time " + now); } catch (SocketTimeoutException ex) { // Do nothing if nothing was sent. } } } catch (BindException e) { // port is in use - increment and try again port++; this.run(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(socket); } }
From source file:Network.Network.java
private String discoverUDPServer() { DatagramSocket c; String foundIP = null;//from ww w .j av a 2 s. c om // Find the server using UDP broadcast try { //Open a random port to send the package c = new DatagramSocket(); c.setBroadcast(true); byte[] sendData = "DISCOVER_BATTLESHIPSERVER_REQUEST".getBytes(); //Try the 255.255.255.255 first try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("255.255.255.255"), 8888); c.send(sendPacket); System.out.println(getClass().getName() + ">>> Request packet sent to: 255.255.255.255 (DEFAULT)"); } catch (Exception e) { } /*// Broadcast the message over all the network interfaces Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; // Don't want to broadcast to the loopback interface } for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress broadcast = interfaceAddress.getBroadcast(); if (broadcast == null) { continue; } // Send the broadcast package! try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888); c.send(sendPacket); } catch (Exception e) { } System.out.println(getClass().getName() + ">>> Request packet sent to: " + broadcast.getHostAddress() + "; Interface: " + networkInterface.getDisplayName()); } }*/ System.out.println(getClass().getName() + ">>> Done looping over all network interfaces. Now waiting for a reply!"); //Wait for a response byte[] recvBuf = new byte[15000]; DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length); c.receive(receivePacket); //We have a response System.out.println(getClass().getName() + ">>> Broadcast response from server: " + receivePacket.getAddress().getHostAddress()); //Check if the message is correct String message = new String(receivePacket.getData()).trim(); if (message.equals("DISCOVER_BATTLESHIPSERVER_RESPONSE")) { //DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller) foundIP = receivePacket.getAddress().getHostAddress(); } //Close the port! c.close(); } catch (IOException ex) { Logger.getLogger(Network.class.getName()).log(Level.SEVERE, null, ex); } return foundIP; }
From source file:com.clustercontrol.notify.util.SendSyslog.java
private void sendUdpMsg(InetAddress ipAddress, int port, String msg) throws IOException { DatagramSocket soc = null; try {//from w w w . j ava2 s . c om // ?????? soc = new DatagramSocket(); // ?? DatagramPacket sendPacket = null; // sendPacket = new DatagramPacket(msg.getBytes(), msg.getBytes().length, ipAddress, port); soc.send(sendPacket); } finally { if (soc != null) { soc.close(); } } }
From source file:org.psit.transwatcher.TransWatcher.java
private String connectAndGetCardIP() { DatagramSocket clientSocket = null, serverSocket = null; try {/*from w w w. ja v a 2 s. c o m*/ String broadcastIP = getBroadcastIP(); setState(broadcastIP == null ? State.NO_WIFI : State.SEARCHING_CARD); notifyMessage("BroadcastIP: " + broadcastIP); // send out broadcast clientSocket = new DatagramSocket(58255); InetAddress IPAddress = InetAddress.getByName(broadcastIP); byte[] sendData = "".getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 55777); clientSocket.send(sendPacket); clientSocket.close(); serverSocket = new DatagramSocket(58255); byte[] receiveData = new byte[256]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.setSoTimeout(3000); serverSocket.receive(receivePacket); serverSocket.close(); notifyMessage("Packet received: " + new String(receiveData)); if (new String(receivePacket.getData()).indexOf("Transcend WiFiSD") >= 0) return receivePacket.getAddress().getHostAddress(); } catch (Exception ex) { notifyMessage("Card handshake unsuccessful. "); notifyException(ex); } finally { if (clientSocket != null) clientSocket.close(); if (serverSocket != null) serverSocket.close(); } return null; }
From source file:vitro.vgw.wsiadapter.WSIAdapterCoap.java
private int dtnResourcesRequest(Node node) throws WSIAdapterException, IOException { int requestMsgId = UNDEFINED_COAP_MESSAGE_ID; // TODO: ??? we will use the packetID as a message ID to return. String proxyAddress = getProxyAddress(node); if (proxyAddress != null) { int packetID = UNDEFINED_COAP_MESSAGE_ID; do { //while loop to avoid a packetID that exists in the array that is to be ignored! packetID = random.nextInt(65535) + 1; } while (timedOut_DTN_CoapMessageIDsList.contains(Integer.valueOf(packetID)) || packetID == UNDEFINED_COAP_MESSAGE_ID); String msgString = Integer.toString(packetID) + "#" + node.getId() + "#" + RESOURCE_REQ + "#wkc"; byte[] msgBytes = new byte[Constants.DTN_MESSAGE_SIZE]; msgBytes = msgString.getBytes(); DatagramPacket sendPacket = new DatagramPacket(msgBytes, msgBytes.length, InetAddress.getByName(proxyAddress), Constants.PROXY_UDPFORWARDER_PORT); DatagramSocket clientSocket = new DatagramSocket(); clientSocket.send(sendPacket); clientSocket.close();/* w w w . j av a 2 s .com*/ requestMsgId = packetID; logger.info("Sent Request: " + msgString); } else { logger.warn("No available proxy for Node " + node.getId() + " is found"); throw new WSIAdapterException("No available proxy for Node " + node.getId() + " is found"); } return requestMsgId; }
From source file:vitro.vgw.wsiadapter.WSIAdapterCoap.java
private int dtnObservationRequest(Node node, Resource resource) throws VitroGatewayException, IOException { int requestMsgId = UNDEFINED_COAP_MESSAGE_ID; // TODO: ??? we will use the packetID as a message ID to return. String proxyAddress = getProxyAddress(node); if (proxyAddress != null) { String moteUriResource = ""; if (MoteResource.containsValue(resource)) { //moteUriResource += MoteResource.getMoteUriResource(resource); String theResourceName = MoteResource.getMoteUriResource(resource); if (theResourceName == null) { logger.error("unsupported resource"); return UNDEFINED_COAP_MESSAGE_ID; }/*from ww w.ja va 2 s. c o m*/ // FOR TCS adapter, we prefer the TEMPERATURE_TCS // FOR WLAB and HAI we prefer the TEMPERATURE_ALT // we do this check because the getMoteUriResource is making a reverse lookup in the hashmap (where two keys point to the same resource) if (theResourceName.compareToIgnoreCase(MoteResource.TEMPERATURE_TCS) == 0) { theResourceName = MoteResource.TEMPERATURE_ALT; } moteUriResource += theResourceName; int packetID = UNDEFINED_COAP_MESSAGE_ID; do { //while loop to avoid a packetID that exists in the array that is to be ignored! packetID = random.nextInt(65535) + 1; } while (timedOut_DTN_CoapMessageIDsList.contains(Integer.valueOf(packetID)) || packetID == UNDEFINED_COAP_MESSAGE_ID); String msgString = packetID + "#" + node.getId() + "#" + RESOURCE_REQ + "#" + moteUriResource; byte[] msgBytes = new byte[Constants.DTN_MESSAGE_SIZE]; msgBytes = msgString.getBytes(); DatagramPacket sendPacket = new DatagramPacket(msgBytes, msgBytes.length, InetAddress.getByName(proxyAddress), Constants.PROXY_UDPFORWARDER_PORT); DatagramSocket clientSocket = new DatagramSocket(); clientSocket.send(sendPacket); clientSocket.close(); requestMsgId = packetID; logger.info("Sent Request: " + msgString); } else { logger.warn("No resource mapping for Node " + node.getId() + " and Resource " + resource.getName()); throw new WSIAdapterException( "No resource mapping for Node " + node.getId() + " and Resource " + resource.getName()); } } else { logger.warn("No available proxy for Node " + node.getId() + " is found"); throw new WSIAdapterException("No available proxy for Node " + node.getId() + " is found"); } return requestMsgId; }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Attempts to retrieve the job managers address in the network through an * IP broadcast. This method should be called by the task manager. * // w w w . java2s .c o m * @return the socket address of the job manager in the network * @throws DiscoveryException * thrown if the job manager's socket address could not be * discovered */ public static InetSocketAddress getJobManagerAddress() throws DiscoveryException { final int magicNumber = GlobalConfiguration.getInteger(MAGICNUMBER_KEY, DEFAULT_MAGICNUMBER); final int discoveryPort = GlobalConfiguration.getInteger(DISCOVERYPORT_KEY, DEFAULT_DISCOVERYPORT); InetSocketAddress jobManagerAddress = null; DatagramSocket socket = null; try { final Set<InetAddress> targetAddresses = getBroadcastAddresses(); if (targetAddresses.isEmpty()) { throw new DiscoveryException("Could not find any broadcast addresses available to this host"); } socket = new DatagramSocket(); LOG.debug("Setting socket timeout to " + CLIENTSOCKETTIMEOUT); socket.setSoTimeout(CLIENTSOCKETTIMEOUT); final DatagramPacket responsePacket = new DatagramPacket(new byte[RESPONSE_PACKET_SIZE], RESPONSE_PACKET_SIZE); for (int retries = 0; retries < DISCOVERFAILURERETRIES; retries++) { final DatagramPacket lookupRequest = createJobManagerLookupRequestPacket(magicNumber); for (InetAddress broadcast : targetAddresses) { lookupRequest.setAddress(broadcast); lookupRequest.setPort(discoveryPort); LOG.debug("Sending discovery request to " + lookupRequest.getSocketAddress()); socket.send(lookupRequest); } try { socket.receive(responsePacket); } catch (SocketTimeoutException ste) { LOG.debug("Timeout wainting for discovery reply. Retrying..."); continue; } if (!isPacketForUs(responsePacket, magicNumber)) { LOG.debug("Received packet which is not destined to this Nephele setup"); continue; } final int packetTypeID = getPacketTypeID(responsePacket); if (packetTypeID != JM_LOOKUP_REPLY_ID) { LOG.debug("Received unexpected packet type " + packetTypeID + ", discarding... "); continue; } final int ipcPort = extractIpcPort(responsePacket); // Replace port from discovery service with the actual RPC port // of the job manager if (USE_IPV6) { // TODO: No connection possible unless we remove the scope identifier if (responsePacket.getAddress() instanceof Inet6Address) { try { jobManagerAddress = new InetSocketAddress( InetAddress.getByAddress(responsePacket.getAddress().getAddress()), ipcPort); } catch (UnknownHostException e) { throw new DiscoveryException(StringUtils.stringifyException(e)); } } else { throw new DiscoveryException(responsePacket.getAddress() + " is not a valid IPv6 address"); } } else { jobManagerAddress = new InetSocketAddress(responsePacket.getAddress(), ipcPort); } LOG.debug("Discovered job manager at " + jobManagerAddress); break; } } catch (IOException ioe) { throw new DiscoveryException(ioe.toString()); } finally { if (socket != null) { socket.close(); } } if (jobManagerAddress == null) { LOG.debug("Unable to discover Jobmanager via IP broadcast"); throw new DiscoveryException("Unable to discover JobManager via IP broadcast!"); } return jobManagerAddress; }
From source file:org.starnub.starnubserver.servers.starbound.UDPProxyServer.java
public void run() { InetAddress IPAddress;/*from w ww. j av a 2 s . com*/ DatagramSocket ds; try { ds = new DatagramSocket(starnubPort); IPAddress = InetAddress.getByName(starboundAddress); } catch (SocketException | UnknownHostException e1) { StarNub.getLogger().cFatPrint("StarNub", ExceptionUtils.getMessage(e1)); e1.printStackTrace(); return; } byte[] request = new byte[1024]; byte[] reply = new byte[4096]; while (!stopping) { try { DatagramPacket from_client = new DatagramPacket(request, request.length); ds.receive(from_client); byte[] real_request = new byte[from_client.getLength()]; System.arraycopy(request, 0, real_request, 0, from_client.getLength()); DatagramPacket sendPacket = new DatagramPacket(real_request, real_request.length, IPAddress, starboundPort); ds.send(sendPacket); DatagramPacket from_server = new DatagramPacket(reply, reply.length); ds.receive(from_server); byte[] real_reply = new byte[from_server.getLength()]; System.arraycopy(reply, 0, real_reply, 0, from_server.getLength()); InetAddress address = from_client.getAddress(); int port = from_client.getPort(); DatagramPacket to_client = new DatagramPacket(real_reply, real_reply.length, address, port); ds.send(to_client); } catch (Exception e) { StarNub.getLogger().cFatPrint("StarNub", ExceptionUtils.getMessage(e)); return; } } }
From source file:com.mobiperf.measurements.RRCTask.java
/** * Send a single packet of the size indicated and wait for a response. * /* w ww . j a v a 2s .c o m*/ * After 7000 ms, time out and return a value of -1 (meaning no response). Otherwise, return the * time from when the packet was sent to when a response was returned by the echo server. * * @param serverAddr Echo server to calculate round trip * @param size size of packet to send in bytes * @param rcvSize size of packets sent from the echo server * @param port where the echo server is listening * @return The round trip time for the packet * @throws IOException */ public static long sendPacket(InetAddress serverAddr, int size, int rcvSize, int port) throws IOException { long startTime = 0; byte[] buf = new byte[size]; byte[] rcvBuf = new byte[rcvSize]; long dataConsumedThisTask = 0; DatagramSocket socket = new DatagramSocket(); DatagramPacket packetRcv = new DatagramPacket(rcvBuf, rcvBuf.length); dataConsumedThisTask += (size + rcvSize); DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port); try { socket.setSoTimeout(7000); startTime = System.currentTimeMillis(); Logger.d("Sending packet, waiting for response "); socket.send(packet); socket.receive(packetRcv); } catch (SocketTimeoutException e) { Logger.d("Timed out, trying again"); socket.close(); return -1; } long endTime = System.currentTimeMillis(); Logger.d("Sending complete: " + endTime); incrementData(dataConsumedThisTask); return endTime - startTime; }