简体   繁体   English

java DatagramSocket 接收数据 Multicast Socket 发送数据

[英]java DatagramSocket receive data Multicast Socket send data

任何人都可以在java中向我展示一个示例来从DatagramSocket接收数据并通过多播套接字发送相同的数据

Sending multicast datagrams发送组播数据报

In order to send any kind of datagram in Java, be it unicast, broadcast or multicast, one needs a java.net.DatagramSocket :为了在 Java 中发送任何类型的数据报,无论是单播、广播还是多播,都需要一个java.net.DatagramSocket

DatagramSocket socket = new DatagramSocket();

One can optionally supply a local port to the DatagramSocket constructor to which the socket must bind.可以选择为套接字必须绑定到的 DatagramSocket 构造函数提供本地端口。 This is only necessary if one needs other parties to be able to reach us at a specific port.仅当需要其他方能够在特定港口与我们联系时才需要这样做。 A third constructor takes the local port AND the local IP address to which to bind.第三个构造函数获取要绑定到的本地端口和本地 IP 地址。 This is used (rarely) with multi-homed hosts where it is important on which network adapter the traffic is received.这(很少)用于多宿主主机,其中接收流量的网络适配器很重要。

 DatagramSocket socket = new DatagramSocket();

byte[] b = new byte[DGRAM_LENGTH];
DatagramPacket dgram;

dgram = new DatagramPacket(b, b.length,
  InetAddress.getByName(MCAST_ADDR), DEST_PORT);

System.err.println("Sending " + b.length + " bytes to " +
  dgram.getAddress() + ':' + dgram.getPort());
while(true) {
  System.err.print(".");
  socket.send(dgram);
  Thread.sleep(1000);
}

Receiving multicast datagrams接收组播数据报

One can use a normal DatagramSocket to send and receive unicast and broadcast datagrams and to send multicast datagrams.可以使用普通的 DatagramSocket 来发送和接收单播和广播数据报以及发送多播数据报。 In order to receive multicast datagrams, however, one needs a MulticastSocket.然而,为了接收多播数据报,需要一个 MulticastSocket。 The reason for this is simple, additional work needs to be done to control and receive multicast traffic by all the protocol layers below UDP.原因很简单,需要做额外的工作来控制和接收 UDP 下所有协议层的多播流量。

byte[] b = new byte[BUFFER_LENGTH];
DatagramPacket dgram = new DatagramPacket(b, b.length);
MulticastSocket socket =
  new MulticastSocket(DEST_PORT); // must bind receive side
socket.joinGroup(InetAddress.getByName(MCAST_ADDR));

while(true) {
  socket.receive(dgram); // blocks until a datagram is received
  System.err.println("Received " + dgram.getLength() +
    " bytes from " + dgram.getAddress());
  dgram.setLength(b.length); // must reset length field!
}

For more Information:想要查询更多的信息:

You've got that back to front.你已经回到了前面。 You receive multicasts through a MulticastSocket , but you don't need to send them that way: you can send them via a DatagramSocket .您通过MulticastSocket接收MulticastSocket ,但您不需要以这种方式发送它们:您可以通过DatagramSocket发送它们。

See the Java Tutorial, Custom Networking trail .请参阅Java 教程,自定义网络跟踪

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM