天天看點

java--------多點傳播程式設計-----MulticastSocket

一、MulticastSocket類

       多點傳播也稱為多點傳播,就是給一組特定的主機(多點傳播組)發送資料。多點傳播通過多點傳播資料報套接MulticastSocket類來實作

             重要的構造方法:

             MulticastSocket()     建立多點傳播套接字

             MulticastSocket(int port)   建立多點傳播套接字并将其綁定到特定端口

             MulticastSocket(SocketAddress bindaddr)   建立綁定到指定套接字位址的MulticastSocket

            常用的方法:

            void joinGroup(InetAddress meastaddr)    加入多點傳播組

            void leaveGroup(InetAddress meastaddr)   離開多點傳播組

            void send(DatagramPacket p) 從此套接字發送資料包

            public void receive(DatagramPacket p)  從此套接字接收資料包

二、代碼實作

發送端程式設計:發送端将在廣播位址為“230.198.112.0”,9876号端口處發送廣播資訊

package org.multicastsocket;
import java.net.InetAddress;
import java.net.DatagramPacket;
import java.net.MulticastSocket;

public class multicastDemo01 extends Thread
{
   String message[] = {"失物招領:有誰在操場丢失鑰匙一串,請到學校廣播站認領。","大風藍色預警:預計今天下午有北風6級,請有關機關和人員做好防範準備。"};
   int port = 9876;//多點傳播的端口
   InetAddress group = null;//多點傳播的組位址
   MulticastSocket mutiSocket = null;//多點傳播套接字
   
   public multicastDemo01()
   {
	  try
	{
		group = InetAddress.getByName("230.198.112.0");//設定廣播組位址
		mutiSocket = new MulticastSocket(port);//多點廣播套接字将在port端口廣播
		mutiSocket.setTimeToLive(1);
		mutiSocket.joinGroup(group);
	}
	catch (Exception e)
	{
		System.out.println("Error:"+e);
	}
   }
   
   public void run()
   {
	   while(true)
	   {
		   try
		{
			DatagramPacket packet = null;
			for(String msg : message)//循環發送每條廣播資訊
			{
				byte buff[] = msg.getBytes();
				packet = new DatagramPacket(buff, buff.length,group,port);
				System.out.println(new String(buff));
				mutiSocket.send(packet);
				sleep(2000);
			}
		}
		catch (Exception e)
		{
			System.out.println("Error:"+e);
		}
	   }
   }
   
   public static void main(String[] args)
   {
	   new multicastDemo01().start();
   }
}
           

接收端程式設計:接收端主機将加入廣播位址為“230.198.112.0”,并在9876号端口處接收廣播資訊

package org.multicastsocket;
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

import java.net.InetAddress;
import java.net.DatagramPacket;
import java.net.MulticastSocket;

public class multicastDemo02 extends JFrame implements Runnable,ActionListener
{
	private static final long serialVersionUID = -5923790809266120014L;
	int port;
	InetAddress group = null;
	MulticastSocket socket = null;
	JButton startButton;
	JButton stopButton;
	JButton cleanButton;
	JTextArea currentMsg;
	JTextArea receiveMsg;
	Thread thread;
	boolean isStop = false;//停止接收廣播資訊的标志
	
	public multicastDemo02()
	{
		setTitle("接收廣播資訊");
		Container container = this.getContentPane();
		startButton = new JButton("開始接收");
		stopButton = new JButton("停止接收");
		cleanButton = new JButton("清空資訊");
		startButton.addActionListener(this);
		stopButton.addActionListener(this);
		cleanButton.addActionListener(this);
		currentMsg = new JTextArea(3,20);//建立3行20列的多行文本框
		currentMsg.setForeground(Color.red);//設定字型顔色為紅色
		receiveMsg = new JTextArea(8,20);//預設字型顔色為黑色
		container.setLayout(new BorderLayout());
		JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT);//建立一帶水準分隔條的面闆
		JScrollPane currScrollPane = new JScrollPane();
		currScrollPane.setViewportView(currentMsg);
		JScrollPane recvScrollPane = new JScrollPane();
		recvScrollPane.setViewportView(receiveMsg);
		currentMsg.setEditable(false);
		receiveMsg.setEditable(false);
		sp.add(currScrollPane);
		sp.add(recvScrollPane);
		container.add(sp,BorderLayout.CENTER);
		JPanel bottomJPanel = new JPanel();
		bottomJPanel.add(startButton);
		bottomJPanel.add(stopButton);
		bottomJPanel.add(cleanButton);
		container.add(bottomJPanel,BorderLayout.SOUTH);
		setSize(500,400);
		setVisible(true);
		thread = new Thread(this);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		port = 9876;
		try
		{
			group = InetAddress.getByName("230.198.112.0");
			socket = new MulticastSocket(port);
			socket.joinGroup(group);
		}
		catch (Exception e)
		{
			
		}
	}
	
	public void actionPerformed(ActionEvent e1)
	{
		if(e1.getSource() == startButton)
		{
			startButton.setEnabled(false);
			stopButton.setEnabled(true);
			if(!(thread.isAlive()))
			{
				thread = new Thread(this);
			}
			try
			{
				thread.start();
				isStop = false;
			}
			catch (Exception ee)
			{
				
			}
		}
		if(e1.getSource() == stopButton)
		{
			startButton.setEnabled(true);
			stopButton.setEnabled(false);
			isStop = true;
		}
		if(e1.getSource() == cleanButton)
		{
			receiveMsg.setText("");
		}
	}
	
	public void run()
	{
	  	while(true)
	  	{
	  		byte buff[] = new byte[8192];
	  		DatagramPacket packet = null;
	  		packet = new DatagramPacket(buff, buff.length,group,port);
	  		try
			{
				socket.receive(packet);
				String message = new String(packet.getData(),0,packet.getLength());
				currentMsg.setText("正在接收的内容:\n"+message);
				receiveMsg.append(message+"\n");
			}
			catch (Exception e)
			{
				
			}
	  		if(isStop == true)
	  		{
	  			break;
	  		}
	  	}
	}
	
	public static void main(String[] args)
	{
		new multicastDemo02();
	}
}
           

三、 效果展示

java--------多點傳播程式設計-----MulticastSocket
java--------多點傳播程式設計-----MulticastSocket