List of usage examples for java.net DatagramSocket send
public void send(DatagramPacket p) throws IOException
From source file:UDP0.java
public static void main(String[] args) throws Exception { byte[] ary = new byte[128]; DatagramPacket pack = new DatagramPacket(ary, 128); if (args[0].charAt(0) == 'r') { // read/*w w w . j a v a 2s . c o m*/ DatagramSocket sock = new DatagramSocket(1111); sock.receive(pack); String word = new String(pack.getData()); System.out.println("From: " + pack.getAddress() + " Port: " + pack.getPort()); System.out.println(word); sock.close(); } else { // write DatagramSocket sock = new DatagramSocket(); pack.setAddress(InetAddress.getByName(args[1])); pack.setData(args[2].getBytes()); pack.setPort(1111); sock.send(pack); sock.close(); } }
From source file:Main.java
public static void main(String args[]) throws IOException { DatagramSocket socket = new DatagramSocket(DAYTIME_PORT); while (true) { byte buffer[] = new byte[256]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); socket.receive(packet);/*from www . j a v a 2 s.co m*/ String date = new Date().toString(); buffer = date.getBytes(); // Get response address/port for client from packet InetAddress address = packet.getAddress(); int port = packet.getPort(); packet = new DatagramPacket(buffer, buffer.length, address, port); socket.send(packet); } }
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 www . j a va2 s.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:ChatClient.java
public static void main(String[] args) throws Exception { int PORT = 4000; byte[] buf = new byte[1000]; DatagramPacket dgp = new DatagramPacket(buf, buf.length); DatagramSocket sk; sk = new DatagramSocket(PORT); System.out.println("Server started"); while (true) { sk.receive(dgp);/*from w w w.ja v a2 s . c o m*/ String rcvd = new String(dgp.getData(), 0, dgp.getLength()) + ", from address: " + dgp.getAddress() + ", port: " + dgp.getPort(); System.out.println(rcvd); BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String outMessage = stdin.readLine(); buf = ("Server say: " + outMessage).getBytes(); DatagramPacket out = new DatagramPacket(buf, buf.length, dgp.getAddress(), dgp.getPort()); sk.send(out); } }
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];//w w w . jav a 2s . co m 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:Main.java
public static void senddatagram(InetAddress target, int port, byte[] outbuf, int len) { try {/* w ww . j av a2 s .c o m*/ DatagramPacket request = new DatagramPacket(outbuf, len, target, port); DatagramSocket socket = new DatagramSocket(); socket.send(request); } catch (SocketException e) { } catch (IOException e) { } }
From source file:Main.java
public static void sendWoLMagicPacket(final String broadcastIp, final String macAddress) { new Thread(new Runnable() { @Override/*from w w w .j a v a 2 s. c o m*/ public void run() { try { byte[] macBytes = getMacBytes(macAddress); byte[] bytes = new byte[6 + 16 * macBytes.length]; for (int i = 0; i < 6; i++) { bytes[i] = (byte) 0xff; } for (int i = 6; i < bytes.length; i += macBytes.length) { System.arraycopy(macBytes, 0, bytes, i, macBytes.length); } InetAddress address = InetAddress.getByName(broadcastIp); DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, 9); DatagramSocket socket = new DatagramSocket(); socket.send(packet); socket.close(); packet = new DatagramPacket(bytes, bytes.length, address, 7); socket = new DatagramSocket(); socket.send(packet); socket.close(); Log.e("WAKE_UP", "Wake-on-LAN packet sent."); final String output = getStringFromBytes(bytes); Log.i("WAKE_UP", output); } catch (Exception e) { Log.e("WAKE_UP", "Failed to send Wake-on-LAN packet: " + e); } } }).start(); }
From source file:SDRecord.java
private static long recordToSocket(DatagramPacket packet, DatagramSocket socket, InetAddress rhost, int destPort) { packet.setPort(destPort);/*from ww w .j a va2 s.c om*/ packet.setAddress(rhost); try { socket.send(packet); } catch (IOException e) { e.printStackTrace(); System.exit(5); } return packet.getLength(); }
From source file:energy.usef.core.util.DateTimeUtil.java
private static synchronized String getUDPInfo(String message) { try {/*w ww.j a v 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:gravity.android.discovery.DiscoveryClient.java
public static ArrayList<DiscoveryServerInfo> findServer(WifiManager mWifi, int port, String token) { ArrayList<DiscoveryServerInfo> ret = new ArrayList<DiscoveryServerInfo>(); try {// w w w .j a v a 2s. co m DatagramSocket clientSocket = new DatagramSocket(); clientSocket.setBroadcast(true); InetAddress IPAddress = Utils.getBroadcastAddress(mWifi); Log.v("DISCOVERY_CLIENT", "broadcast addr " + IPAddress.getHostAddress()); byte[] receiveData = new byte[2048]; byte[] sendData = new byte[128]; sendData = token.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); Log.v("DISCOVERY_CLIENT", "sent " + token); clientSocket.send(sendPacket); long t1 = System.currentTimeMillis(); while (System.currentTimeMillis() - t1 <= 4000) // 4 secondi { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); try { clientSocket.setSoTimeout(500); clientSocket.receive(receivePacket); if (receivePacket.getAddress() != null && receivePacket.getAddress().getHostAddress() != null) { String discovered_name, discovered_ip; int discovered_port; String received = new String(receivePacket.getData()); if (received != null) { received = received.trim().substring(0, receivePacket.getLength()).trim(); Log.d("Recieved Msg Packet:", received); //StringTokenizer st = new StringTokenizer(received, ","); //Gravity Code JSONObject recievedJson = new JSONObject(received); try { //discovered_name = st.nextToken(); discovered_name = recievedJson.getString("name"); //Gravity code discovered_ip = receivePacket.getAddress().getHostAddress(); //discovered_port = Integer.parseInt(st.nextToken()); discovered_port = recievedJson.getInt("port_to_share"); //Gravity code Log.v("DISCOVERY_CLIENT", "discovered " + discovered_name + ", " + discovered_ip + ":" + discovered_port); boolean add = true; if (ret.size() > 0) { for (DiscoveryServerInfo dsi : ret) { if (dsi != null && dsi.ip.equals(discovered_ip)) { add = false; break; } } } if (add) { ret.add(new DiscoveryServerInfo(discovered_name, discovered_ip, discovered_port)); } } catch (NoSuchElementException nsee) { Log.v("DISCOVERY_CLIENT", nsee.getLocalizedMessage()); } } } } catch (SocketTimeoutException tex) { /* ignored */ } } clientSocket.close(); } catch (Exception ex) { ex.printStackTrace(); Log.e("DISCOVERY_CLIENT", ex.toString()); } return ret; }