1. 程式人生 > >Java-UDP程式編寫(實現組播)

Java-UDP程式編寫(實現組播)

1.播報廣播端

package test;

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

public class Weather extends Thread{
	String weather = "今晚團建";
	int port = 9898;
	InetAddress ipAddress = null;
	MulticastSocket socket = null;
	/**
	 * 建立廣播資料的主機,廣播的主機和接收廣播的主機必須加入到同一組,
	 * 地址範圍是224.0.0.0~224.255.255.255
	 */
	
	
	Weather(){					//構造方法
		try {
			ipAddress = InetAddress.getByName("224.255.10.0");
			socket = new MulticastSocket(port);			//例項化多點廣播套接字
			socket.setTimeToLive(1);				//指定傳送範圍是本地網路
			socket.joinGroup(ipAddress);   			//加入廣播組
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void run() {
		while (true) {
			DatagramPacket packet = null;			//宣告datagrampacket物件
			byte data[] = weather.getBytes();     //將字串轉化為位元組陣列
			packet = new DatagramPacket(data, data.length,ipAddress,port);			//將位元組陣列封裝進資料包裡
			System.out.println(new String(data));    //將位元組陣列轉化為字串列印在控制檯
			try {
				socket.send(packet);			//傳送資料包
				sleep(3000);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main (String[] args) {
		Weather w = new Weather();		//建立本類物件
		w.start();						//啟動執行緒
	}
}

2.接收廣播端

package test;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;

public class Receive extends JFrame implements Runnable,ActionListener{  		//實現runable,actionlistener介面
	int port;
	InetAddress groupAddress = null;
	MulticastSocket multicastSocket = null;
	JButton startButton = new JButton("開始接收");
	JButton stopButton = new JButton("結束接收");
	JTextArea inceAr = new JTextArea(5,10);
	JTextArea inced = new JTextArea(5,10);
	Thread thread;
	boolean b = false;
	/**
	 * 接收廣播端
	 */
	
	public Receive () {
		super("客戶端接收");   						//繼承,設定視窗標題為客戶端接收
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		thread = new Thread(this);
		startButton.addActionListener(this);
		stopButton.addActionListener(this);
		inceAr.setForeground(Color.blue);
		inced.setForeground(Color.red);					//設定文字的顏色
		JPanel jPanel = new JPanel();
		JPanel jPanel2 = new JPanel();
		JScrollPane jScrollPane = new JScrollPane(inced);   //將文字域新增進滾動面板
		jPanel.add(startButton);
		jPanel.add(stopButton);
		jPanel2.add(jScrollPane,BorderLayout.WEST);
		jPanel2.add(inceAr,BorderLayout.EAST);
		add(jPanel,BorderLayout.SOUTH);
		add(jPanel2,BorderLayout.CENTER);
		validate();								//重新整理,如果之前設定了大小,會重新整理成為設定的大小
		port = 9898;
		try {
			groupAddress = InetAddress.getByName("224.255.10.0");
			multicastSocket = new MulticastSocket(port);		//繫結多點廣播套接字
			multicastSocket.joinGroup(groupAddress);
		} catch (Exception e) {
			e.printStackTrace();
		}
		setBounds(0,0,400,200);			//設定佈局
		setVisible(true);				//將佈局設定為顯示狀態
	}
	
	public void run() {
		while (true) {
			byte[] data = new byte[1024];
			DatagramPacket packet = null;
			packet = new DatagramPacket(data, data.length,groupAddress,port);					//將位元組陣列封裝進資料包
			try {
				multicastSocket.receive(packet);
				String messageString = new String(packet.getData(),0,packet.getLength());  		//將資料包裡的資料轉化為字串
				inceAr.setText("正在接收的內容是:\n"+messageString);			//設定正在接收文字內容域
				inced.append(messageString + "\n");				//設定為每條資訊為一行
//				validate();
				System.out.println("asasas");
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			if (b == true) {
				break;						//當變數為true時退出迴圈
			}   
			
		}
	}
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == startButton) {
			startButton.setBackground(Color.red);
			stopButton.setBackground(Color.yellow);
			if (! (thread.isAlive())) {
				thread = new Thread(this);
			}
			thread.start();					//啟動執行緒
		}
		if (e.getSource() == stopButton) {
			startButton.setBackground(Color.yellow);
			stopButton.setBackground(Color.red);
			b = true;
		}
	}
	
	public static void  main(String[] args) {
		Receive receive = new Receive();
//		receive.setSize(400,200);
	}
}

3.接收端接收廣播資料
<1>廣播端開啟
在這裡插入圖片描述<2>接收端開啟
在這裡插入圖片描述