服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

使用java制作多点发送程序


  ip协议是internet上所有信息的传播手段,udp(user datagram protocol,用户数据报协议)数据报被封装在ip包中,发送到网络上适当的机器。众所周知,大多数ip使用单点发送,即从一个主机发送一个包到另一个主机上。然而,ip协议也具有多点发送的能力,若要使用多点发送时,一个报文标有一组目标主机地址,当报文发出后,整个组都能收到。为支持多点发送,一定范围的ip地址被单独划分出来。这些ip地址是d类地址,其范围是224.0.0.0至239.255.255.255。

   ip多点发送(或多点广播)是一种相当新的技术,它是对简单广播的改进。多点广播功能类似于一个单一信息发送到多个接收者的广播,但仅发送给那些等待它的接收者。其思想就是设置一组网络地址作为多点广播地址,其范围是225.0.0.0到239.255.255.255。每一个多点广播地址都被看作一个组。当用户需要从某个地址信息时,加入到该组即可。例如,可能为其股票报价系统设置了地址225.23.32.36作为多点广播地址,如果一个想要接收股票查询报价程序,必须加入到225.23.32.36组中。

  制作多点发送的基本知识

  在使用java进行多点发送时,它的multicastsocket类是实现这一功能的关键。multicastsocket类允许用户发送和接收使用多点发送ip的数据报。若要发送或接收多点广播数据,必须首先创建一个多点广播套接字(多点广播套接字类似于数据报套接字,事实上multicastsocket是datagramsocket的一个子类)。若要发送一个数据报时,可使用缺省的端口号创建多点广播套接字,也可以在构造器指定端口号来创建多点广播套接字:

    public multicastsocket()throws ioexception

    public multicastsocket(int portnumber)throws ioexception

  要加入到一个多点广播地址,可使用jiongroup方法;若要脱离一个组,相使用leavegroup方法:

    public void jiongroup(inetaddress multicastaddr)throws ioexception

    public void leavegroup(inetaddress multicastaddr)throws ioexception

  在某些系统中,可能有多重网络接口。这可能会对多点广播带来问题,因为用户需要在一个指定的接口上侦听,通过调用setinterface可选择多点广播套接字所使用的接口:

    public void setinterface(inetaddress interface)throws socketexception

  通过调用getinterface方法可查询多点广播套接字的接口:

    public inetaddress getinterface()throws socketexception

  用户在发送多点发送的数据时,使用send方法:

    public synchronized void send(datagrampacket packet, byte timetolive)throws ioexception

其中ttl值指定了数据包应该跨过多少个网络,当ttl为0时,指定数据包应停留在本地主机;当ttl的值为1时,指定数据包发送到本地网络;当ttl的值为32时,意味着只应发送到本站点的网络上;当ttl为64时,意味着数据包应保留在本地区;当ttl的值为128时,意味着数据应保留在本大洲;当ttl为255时,意味着数据包应发送到所有地方;若使用缺省的send方法时,ttl的值为1。
  制作多点发送应用程序

  下面就运用java制作一个多点发送应用程序。其中程序1(multicastcastsender.java)是一个发送数据报到一个指定多点发送ip地址的程序,该程序运行时使用两个参数:第一个指定发送数据报的多点发送ip地址,另一个则指定侦听应用程序的udp端口。其中main()方法保证了这些参数收到后,实例化一个multicastsender对象。另外,构造器使用多点发送ip地址的string对象,创建一个inetaddress实例,然后再在动态分配的端口上为发送数据报创建一个multicastsocket,然后构造器进入一个while循环,从标准输入上逐入。该程序将每一行的前512个字节包装到一标有地址的datagrampacket中,并通过multicastsocket发送该数据报。

  其中程序multicastsender.java的源代码如下:

  import java.net.*; // import package names used.

  import java.io.*;

  class multicastsender {

    private static final byte ttl = 1;

    private static final int datagram_bytes = 1024;

    private int mulcastport;

    private inetaddress mulcastip;

    private bufferedreader input;

    private multicastsocket mulcastsocket;

    public static void main(string[] args) {

     // this must be the same port and ip address used by the receivers.

     if (args.length != 2) {

      system.out.print("usage: multicastsender " + " /n/t                can be one of 224.x.x.x " + "- 239.x.x.x/n");

      system.exit(1);

    }

    multicastsender send = new multicastsender(args);

    system.exit(0);

   }

  public multicastsender(string[] args) {

    datagrampacket mulcastpacket; // udp datagram.

    string nextline; // line from stdin.

    byte[] mulcastbuffer; file:// buffer for datagram.

    byte[] linedata; // the data typed in.

    int sendlength; file:// length of line.

    input = new bufferedreader(new inputstreamreader(system.in));

    try {

      // create a multicasting socket.

      mulcastip = inetaddress.getbyname(args[0]);

      mulcastport = integer.parseint(args[1]);

      mulcastsocket = new multicastsocket();

      } catch(unknownhostexception excpt) {

         system.err.println("unknown address: " + excpt);

         system.exit(1);

         } catch(ioexception excpt) {

           system.err.println("unable to obtain socket: " + excpt);

           system.exit(1);

             }

     try {

       file:// loop and read lines from standard input.

       while ((nextline = input.readline()) != null) {

         mulcastbuffer = new byte[datagram_bytes];

         file:// if line is longer than your buffer, use the length of the buffer available.

         if (nextline.length() > mulcastbuffer.length) {

          endlength = mulcastbuffer.length;

          // otherwise, use the line's length.

          }
         else {

          sendlength = nextline.length();

           }

         // convert the line of input to bytes.

         linedata = nextline.getbytes();

         // copy the data into the blank byte array
         file://which you will use to create the datagrampacket.

         for (int i = 0; i < sendlength; i++) {

           mulcastbuffer[i] = linedata[i];

          }

         mulcastpacket=new datagrampacket (mulcastbuffer, mulcastbuffer.length,                              mulcastip, mulcastport);

         // send the datagram.

      try {

        system.out.println("sending:/t" + nextline);

        mulcastsocket.send(mulcastpacket,ttl);

        } catch(ioexception excpt) {

          system.err.println("unable to send packet: " + excpt);

          }

        }

       } catch(ioexception excpt) {

         system.err.println("failed i/o: " + excpt);

         }

       mulcastsocket.close(); file:// close the socket.

     }

    }
  程序2(multicastreceiver.java)通过接收多点发送的数据报实现了发送者。该应用程序有两个参数,这两个参数必须对应于ip地址和用来激活multicastsender的端口。main()方法首先检查命令的参数,然后创建一个multicastreceiver对象。该对象的构造器用在激活该应用程序的端口上创建一个inetaddress和一个multicastsocket。在包含于inetaddress的地址加入多点发送者,然后进入一个循环。该对象的构造器从一个套接字接收数据报并打印出包含在数据报中数据,包括发送数据包的计算机和端口。

   程序2(multicastreceiver)的源代码如下:

    import java.net.*; // import package names used.

    import java.io.*;

    class multicastreceiver {

     private static final int datagram_bytes = 1024;

     private int mulcastport;

     private inetaddress mulcastip;

     private multicastsocket mulcastsocket;

     private boolean keepreceiving = true;

     public static void main(string[] args) {

      // this must be the same port and ip address used by the sender.

      if (args.length != 2) {

       system.out.print("usage: multicastreceiver /n/t can be one of " + "224.x.x.x - 239.x.x.x/n");

       system.exit(1);

      }

     multicastreceiver send = new multicastreceiver(args);

       system.exit(0);

       }

     public multicastreceiver(string[] args) {

      datagrampacket mulcastpacket; // packet to receive.

      byte[] mulcastbuffer; // byte[] array buffer

      inetaddress fromip; file:// sender address.

      int fromport; // sender port.

      string mulcastmsg; // string of message.

     try {

       // first, set up your receiving socket.

      mulcastip = inetaddress.getbyname(args[0]);

      mulcastport = integer.parseint(args[1]);

      mulcastsocket = new multicastsocket(mulcastport);

      // join the multicast group.

      mulcastsocket.joingroup(mulcastip);

      } catch(unknownhostexception excpt) {

       system.err.println("unknown address: " + excpt);

       system.exit(1);

      } catch(ioexception excpt) {

       system.err.println("unable to obtain socket: " + excpt);

       system.exit(1);

      }

      while (keepreceiving) {

      try {

       // create a new datagram.

       mulcastbuffer = new byte[datagram_bytes];

       mulcastpacket = new datagrampacket(mulcastbuffer, mulcastbuffer.length);

       // receive the datagram.

       mulcastsocket.receive(mulcastpacket);

       fromip = mulcastpacket.getaddress();

       fromport = mulcastpacket.getport();

       mulcastmsg = new string(mulcastpacket.getdata());

       // print out the data.

       system.out.println("received from " + fromip + " on port " + fromport + ": " +                   mulcastmsg);

       } catch(ioexception excpt) {

      system.err.println("failed i/o: " + excpt);

      }

     }

    try {

     mulcastsocket.leavegroup(mulcastip); file:// leave the group.

      } catch(ioexception excpt) {

     system.err.println("socket problem leaving group: " + excpt);

     }

     mulcastsocket.close();    // close the socket.

    }

   public void stop() {

    if (keepreceiving) {

     keepreceiving = false;

     }

    }

   }

  若要运用该应用程序,先编译multicastsender和multicastreceiver,然后将multicastreceiver传送到其它机器,以便能够演示多个参与者接收报文的情况,最后java解释器运行该应用程序。例如:要向225.2.32.6组在端口1111上发送多点发送报文,应按如下方法进行:

   -/class ->java multicastsender225.2.32.6 1111

   here is just to test multicast message.

   sending: here is just to test multicast message.

   do you received it?

   sending: do you received it?

要接收这些报文,应在一个或多个系统上运行multicastreceiver应用程序,这些系统应该加入同一个多点发送组225.2.32.6,并在相同的端口1111上侦听:

   -/class ->java multicastreceiver 225.2.32.6 1111

   received from 225.106.36.32 on port 32911: here is just to test multicast message.

   received from 225.106.36.32 on port 32911: do you received it?

扫描关注微信公众号