Чтение данных по UDP (multicast)
- package javaapplication1;
- import java.io.IOException;
- import static java.lang.System.out;
- import java.net.DatagramPacket;
- import java.net.InetAddress;
- import java.net.InetSocketAddress;
- import java.net.MulticastSocket;
- import java.net.SocketAddress;
- import java.net.SocketException;
- import java.net.UnknownHostException;
- /**
- * @author Naik
- */
- public class JavaApplication1 {
- /**
- * Adress:
- *
- * udp://@238.100.100.33:1234
- */
- public static void main(String[] args) {
- int port = 1234;
- String host = "238.100.100.33";
- try {
- MulticastSocket mCastSock = new MulticastSocket(port);
- mCastSock.setSoTimeout(5000);
- InetAddress addr = InetAddress.getByName(host);
- SocketAddress sockAddr = new InetSocketAddress(addr, port);
- mCastSock.joinGroup(addr);
- byte[] buf = new byte[1024];
- DatagramPacket packet = new DatagramPacket(buf, buf.length);
- mCastSock.receive(packet);
- while (true) {
- out.println("Data: " + new String(buf, "ascii"));
- }
- } catch (SocketException ex) {
- ex.printStackTrace();
- } catch (UnknownHostException ex) {
- ex.printStackTrace();
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- }
Будет работать только в локальной сети.