java--------多播编程-----MulticastSocket

本文介绍了Java中的多播编程,重点讲解了MulticastSocket类的使用,包括构造方法和关键方法如joinGroup、leaveGroup、send及receive。示例中展示了如何创建发送端,将广播信息发送到多播地址230.198.112.0的9876端口。
摘要由CSDN通过智能技术生成

一、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();
	}
}

三、 效果展示



  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值