java DatagramSocket 接收数据 Multicast Socket 发送数据 [英] java DatagramSocket receive data Multicast Socket send data

查看:33
本文介绍了java DatagramSocket 接收数据 Multicast Socket 发送数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能给我看一个java中的例子来从DatagramSocket接收数据并通过多播套接字发送相同的数据

can anyone show me an example in java to receive data from DatagramSocket and sending same data through Multicast Socket

推荐答案

发送多播数据报

为了在 Java 中发送任何类型的数据报,无论是单播、广播还是多播,都需要一个 java.net.DatagramSocket:

In order to send any kind of datagram in Java, be it unicast, broadcast or multicast, one needs a java.net.DatagramSocket:

DatagramSocket socket = new DatagramSocket();

可以选择为套接字必须绑定到的 DatagramSocket 构造函数提供本地端口.仅当需要其他方能够在特定港口与我们联系时才需要这样做.第三个构造函数获取本地端口和要绑定的本地 IP 地址.这(很少)用于多宿主主机,其中接收流量的网络适配器很重要.

One can optionally supply a local port to the DatagramSocket constructor to which the socket must bind. 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. 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);
}

接收多播数据报

可以使用普通的 DatagramSocket 来发送和接收单播和广播数据报以及发送多播数据报.然而,为了接收多播数据报,需要一个 MulticastSocket.这样做的原因很简单,需要做额外的工作来控制和接收 UDP 下所有协议层的多播流量.

One can use a normal DatagramSocket to send and receive unicast and broadcast datagrams and to send multicast datagrams. In order to receive multicast datagrams, however, one needs a 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.

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!
}

更多信息:

这篇关于java DatagramSocket 接收数据 Multicast Socket 发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆