List of usage examples for java.net DatagramSocket receive
public synchronized void receive(DatagramPacket p) throws IOException
From source file:Main.java
public static void main(String[] args) throws Exception { final int LOCAL_PORT = 12345; final String SERVER_NAME = "localhost"; DatagramSocket udpSocket = new DatagramSocket(LOCAL_PORT, InetAddress.getByName(SERVER_NAME)); System.out.println("Created UDP server socket at " + udpSocket.getLocalSocketAddress() + "..."); while (true) { System.out.println("Waiting for a UDP packet..."); DatagramPacket packet = new DatagramPacket(new byte[1024], 1024); udpSocket.receive(packet); displayPacketDetails(packet);/*from www . java 2 s .co m*/ udpSocket.send(packet); } }
From source file:Main.java
public static void main(String[] args) throws Exception { DatagramSocket udpSocket = new DatagramSocket(); String msg = null;// www .ja va 2 s. c o m BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please enter a message (Bye to quit):"); while ((msg = br.readLine()) != null) { if (msg.equalsIgnoreCase("bye")) { break; } DatagramPacket packet = Main.getPacket(msg); udpSocket.send(packet); udpSocket.receive(packet); displayPacketDetails(packet); System.out.print("Please enter a message (Bye to quit):"); } udpSocket.close(); }
From source file:UDPReceive.java
public static void main(String args[]) { try {/* www . j a v a 2s .com*/ int port = 90; // Create a socket to listen on the port. DatagramSocket dsocket = new DatagramSocket(port); // Create a buffer to read datagrams into. If a // packet is larger than this buffer, the // excess will simply be discarded! byte[] buffer = new byte[2048]; // Create a packet to receive data into the buffer DatagramPacket packet = new DatagramPacket(buffer, buffer.length); // Now loop forever, waiting to receive packets and printing them. while (true) { // Wait to receive a datagram dsocket.receive(packet); // Convert the contents to a string, and display them String msg = new String(buffer, 0, packet.getLength()); System.out.println(packet.getAddress().getHostName() + ": " + msg); // Reset the length of the packet before reusing it. packet.setLength(buffer.length); } } catch (Exception e) { System.err.println(e); } }
From source file:ChatClient.java
public static void main(String[] args) throws Exception { DatagramSocket s = new DatagramSocket(); byte[] buf = new byte[1000]; DatagramPacket dp = new DatagramPacket(buf, buf.length); InetAddress hostAddress = InetAddress.getByName("localhost"); while (true) {/*from ww w.j a v a 2s.c o m*/ BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String outMessage = stdin.readLine(); if (outMessage.equals("bye")) break; String outString = "Client say: " + outMessage; buf = outString.getBytes(); DatagramPacket out = new DatagramPacket(buf, buf.length, hostAddress, 9999); s.send(out); s.receive(dp); String rcvd = "rcvd from " + dp.getAddress() + ", " + dp.getPort() + ": " + new String(dp.getData(), 0, dp.getLength()); System.out.println(rcvd); } }
From source file:UDPReceive.java
public static void main(String args[]) { try {//ww w. j a v a 2s . c o m if (args.length != 1) throw new IllegalArgumentException("Wrong number of args"); // Get the port from the command line int port = Integer.parseInt(args[0]); // Create a socket to listen on the port. DatagramSocket dsocket = new DatagramSocket(port); // Create a buffer to read datagrams into. If anyone sends us a // packet containing more than will fit into this buffer, the // excess will simply be discarded! byte[] buffer = new byte[2048]; // Create a packet to receive data into the buffer DatagramPacket packet = new DatagramPacket(buffer, buffer.length); // Now loop forever, waiting to receive packets and printing them. for (;;) { // Wait to receive a datagram dsocket.receive(packet); // Decode the bytes of the packet to characters, using the // UTF-8 encoding, and then display those characters. String msg = new String(buffer, 0, packet.getLength(), "UTF-8"); System.out.println(packet.getAddress().getHostName() + ": " + msg); // Reset the length of the packet before reusing it. // Prior to Java 1.1, we'd just create a new packet each time. packet.setLength(buffer.length); } } catch (Exception e) { System.err.println(e); System.err.println(usage); } }
From source file:DaytimeClient.java
public static void main(String args[]) throws java.io.IOException { // Figure out the host and port we're going to talk to String host = args[0];/*from ww w . j a v a 2 s .com*/ int port = 13; if (args.length > 1) port = Integer.parseInt(args[1]); // Create a socket to use DatagramSocket socket = new DatagramSocket(); // Specify a 1-second timeout so that receive() does not block forever. socket.setSoTimeout(1000); // This buffer will hold the response. On overflow, extra bytes are // discarded: there is no possibility of a buffer overflow attack here. byte[] buffer = new byte[512]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length, new InetSocketAddress(host, port)); // Try three times before giving up for (int i = 0; i < 3; i++) { try { // Send an empty datagram to the specified host (and port) packet.setLength(0); // make the packet empty socket.send(packet); // send it out // Wait for a response (or timeout after 1 second) packet.setLength(buffer.length); // make room for the response socket.receive(packet); // wait for the response // Decode and print the response System.out.print(new String(buffer, 0, packet.getLength(), "US-ASCII")); // We were successful so break out of the retry loop break; } catch (SocketTimeoutException e) { // If the receive call timed out, print error and retry System.out.println("No response"); } } // We're done with the channel now socket.close(); }
From source file:SDRecord.java
public static void main(String[] args) { boolean recordToInf = false; long recordTo = 0, txsize = 0, wr = 0, max = 0; int sourcePort = 0, destPort = 0; String val; OutputStream writer = null;/*from ww w . j a va 2 s . co m*/ InetAddress rhost = null, lhost = null; DatagramSocket socket = null; //Default values int buffSize = 1500; try { lhost = InetAddress.getByName("0.0.0.0"); } catch (UnknownHostException e1) { System.err.println("ERROR!: Host not reconized"); System.exit(3); } recordToInf = true; sourcePort = 7355; Options options = new Options(); options.addOption("m", true, "Minutes to record, default is no limit"); options.addOption("l", true, "Bind to a specific local address, default is 0.0.0.0"); options.addOption("p", true, "Local port to use, default is 7355"); options.addOption("r", true, "Remote address where to send data"); options.addOption("d", true, "Remote port, to use with -r option"); options.addOption("f", true, "Output file where to save the recording"); options.addOption("s", true, "Stop recording when reaching specified MBs"); options.addOption("h", false, "Help"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e1) { System.err.println("ERROR!: Error while parsing the command line"); System.exit(1); } if (cmd.hasOption("m")) { val = cmd.getOptionValue("m"); try { if (Long.parseLong(val) < 0) { System.err.println("ERROR!: -m argument value cannot be negative"); System.exit(3); } recordTo = System.currentTimeMillis() + (Long.parseLong(val) * 60000); recordToInf = false; } catch (NumberFormatException e) { System.err.println("ERROR!: -m argument not an integer"); System.exit(3); } } if (cmd.hasOption("l")) { val = cmd.getOptionValue("l"); try { lhost = InetAddress.getByName(val); } catch (UnknownHostException e) { System.err.println("ERROR!: Host not reconized"); System.exit(3); } } if (cmd.hasOption("p")) { val = cmd.getOptionValue("p"); try { sourcePort = Integer.parseInt(val); } catch (NumberFormatException e) { System.err.println("ERROR!: -p argument not an integer"); System.exit(3); } } if (cmd.hasOption("r")) { val = cmd.getOptionValue("r"); try { rhost = InetAddress.getByName(val); } catch (UnknownHostException e) { System.err.println("ERROR!: Host not reconized"); System.exit(3); } } if (cmd.hasOption("d")) { val = cmd.getOptionValue("d"); try { destPort = Integer.parseInt(val); } catch (NumberFormatException e) { System.err.println("-ERROR!: -d argument not an integer"); System.exit(3); } } if (cmd.hasOption("f")) { val = cmd.getOptionValue("f"); try { writer = new FileOutputStream(val); } catch (FileNotFoundException e) { System.err.println("ERROR!: File not found"); System.exit(3); } } if (cmd.hasOption("s")) { val = cmd.getOptionValue("s"); try { max = (long) (Double.parseDouble(val) * 1000000); } catch (NumberFormatException e) { System.err.println("ERROR!: -s argument not valid"); System.exit(3); } if (Double.parseDouble(val) < 0) { System.err.println("ERROR!: -s argument value cannot be negative"); System.exit(3); } } if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("SDRecord", options); System.exit(0); } try { socket = new DatagramSocket(sourcePort, lhost); //socket options socket.setReuseAddress(true); } catch (SocketException e) { e.printStackTrace(); System.exit(3); } byte[] buffer = new byte[buffSize]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); System.err.println("Listening " + lhost.toString() + " on port " + sourcePort); while (recordToInf == true || System.currentTimeMillis() <= recordTo) { //Stop recording when reaching max bytes if (max != 0 && txsize >= max) break; packet.setData(buffer); try { socket.receive(packet); } catch (IOException e) { e.printStackTrace(); System.exit(4); } //Ignoring packets with no data if (basicFilter(packet) == null) continue; if (writer == null && rhost == null) wr = recordToStdout(packet); if (writer != null) wr = recordToFile(packet, writer); if (rhost != null) wr = recordToSocket(packet, socket, rhost, destPort); txsize += wr; System.err .print("\r" + formatSize(txsize) + " transferred" + "\033[K" + "\t Press Ctrl+c to terminate"); } //closing socket and exit System.err.print("\r" + formatSize(txsize) + " transferred" + "\033[K"); socket.close(); System.out.println(); System.exit(0); }
From source file:Main.java
private static void receive(Map<Integer, byte[]> map, DatagramSocket socket, int[] length) { byte[] b = new byte[limit + 4]; DatagramPacket p = new DatagramPacket(b, b.length); try {/* w w w .ja v a 2s. c o m*/ socket.receive(p); } catch (IOException ex) { ex.printStackTrace(); } if (p.getLength() != 0) { ByteBuffer buf = ByteBuffer.wrap(b); int key = buf.getInt(); byte[] bytes = new byte[p.getLength() - 4]; length[0] += bytes.length; buf.get(bytes); map.put(key, bytes); receive(map, socket, length); } }
From source file:energy.usef.core.util.DateTimeUtil.java
private static synchronized String getUDPInfo(String message) { try {/*from w ww. j av a 2 s . com*/ LOGGER.debug("SENDING: {}", message); byte[] buf = message.getBytes(); InetAddress address = InetAddress.getByName(serverIp); DatagramSocket socket = new DatagramSocket(); socket.send(new DatagramPacket(buf, buf.length, address, port)); DatagramPacket result = new DatagramPacket(new byte[PACKAGE_BUFFER], PACKAGE_BUFFER); socket.disconnect(); socket.setSoTimeout(RESPONSE_TIMEOUT); socket.receive(result); socket.disconnect(); socket.close(); String resultStr = new String(result.getData()).trim(); LOGGER.debug("RECEIVED: {} ", resultStr); errorCount = 0; return resultStr; } catch (IOException e) { LOGGER.error(e.getMessage(), e); errorCount++; if (errorCount >= MAX_ERROR_COUNT) { LOGGER.error("Unable to run simulation correctly."); System.exit(1); } } return null; }
From source file:org.echocat.jomon.net.dns.DnsServer.java
private static void receive(@Nonnull DatagramSocket sock, @Nonnull DatagramPacket indp) throws IOException { try {/*from www . ja v a2s.c o m*/ sock.receive(indp); } catch (final SocketException e) { if (sock.isClosed()) { final InterruptedIOException toThrow = new InterruptedIOException(); toThrow.initCause(e); throw toThrow; } else { throw e; } } }