This is a UDP network program. The following presents a multicast datagram program, which is actually a new technology.
[java]
- package com.han;
- import java.net.*;
- /**
- * This is a UDP network program.
- * The following presents a multicast datagram program,
- * which is actually a new technology.
- *
- * @author HAN
- *
- */
- public class Weather extends Thread{
- String weather ="節目預告: 八點有大型晚會,請收聽";
- int port =9898;
- InetAddress iaddress;//沒法初始化,這裡只能聲明。因為初始化new對象時要拋出異常所以在成員變量區域是語法通不過的。
- MulticastSocket socket;
- //在構造方法中初始化成員變量
- Weather(){
- try {
- //A multicast group is specified by a class D IP address
- //and by a standard UDP port number.
- //Class D IP addresses are in the range 224.0.0.0 to 239.255.255.255, inclusive.
- //The address 224.0.0.0 is reserved and should not be used.
- iaddress=InetAddress.getByName("233.0.0.0");
- socket=new MulticastSocket(port);
- socket.setTimeToLive(1);
- socket.joinGroup(iaddress);
- }catch(Exception e){
- e.printStackTrace();
- }
-
- }
- @Override //最簡單的方法也就是建立一個線程來運行
- public void run(){
- while(true){
- byte[] data=weather.getBytes();
- DatagramPacket packet=new DatagramPacket(data,data.length,iaddress,port);
- // System.out.println(weather);
- System.out.println(new String(data));
- try {
- socket.send(packet);
- sleep(3000);//線程休眠3秒
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- public static void main(String[] args){
- Weather w=new Weather();
- w.start();
- }
- }
This is the receive part.
[java]
- package com.han;
- import java.awt.BorderLayout;
- import java.awt.Color;
- import java.awt.event.*;
- import java.io.IOException;
- import java.net.DatagramPacket;
- import java.net.InetAddress;
- import java.net.MulticastSocket;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JPanel;
- import javax.swing.JScrollPane;
- import javax.swing.JTextArea;
- /**
- * This is the receive part.
- * @author HAN
- *
- */
- public class Receive extends JFrame implements Runnable, ActionListener{
- private static final long serialVersionUID = 3362377947503474102L;
- int port=9898;
- InetAddress group;
- MulticastSocket socket; //socket sends and receives the packet.
- DatagramPacket packet;
- JButton ince=new JButton("開始接收");
- JButton stop=new JButton("停止接收");
- JTextArea inceAr=new JTextArea(10,20);
- JTextArea inced=new JTextArea(10,20);
- Thread thread;
- boolean b = false;
- byte[] buf=new byte[30];// If the message is longer than the packet's length, the message is truncated.
-
- //在構造方法中設置具體參數特性,也就是初始化
- public Receive(){
- super("廣播數據報");
- thread=new Thread(this);
- ince.addActionListener(this);
- stop.addActionListener(this);
- inceAr.setForeground(Color.blue);
- JPanel north=new JPanel();
- north.add(ince);
- north.add(stop);
- add(north,BorderLayout.NORTH);
- JPanel center=new JPanel();
- JScrollPane sp=new JScrollPane(inceAr);
- JScrollPane sp2=new JScrollPane(inced);
- inceAr.setLineWrap(true);
- inceAr.setEditable(false);
- inced.setLineWrap(true);
- inced.setEditable(false);
- center.add(sp);
- center.add(sp2);
- add(center,BorderLayout.CENTER);
- pack(); //JFrame inherited from Window
- validate();
- setVisible(true);
- setDefaultCloseOperation(EXIT_ON_CLOSE);
- try {
- socket=new MulticastSocket(port);
- //A multicast group is specified by a class D IP address
- //and by a standard UDP port number.
- //Class D IP addresses are in the range 224.0.0.0 to 239.255.255.255, inclusive.
- //The address 224.0.0.0 is reserved and should not be used.
- group=InetAddress.getByName("233.0.0.0");
- socket.joinGroup(group);
- packet=new DatagramPacket(buf,buf.length);
-
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- }
- @Override
- public void run(){
- while(true){
- try {
- socket.receive(packet);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- // String message=new String(buf);
- String message=new String(packet.getData(),0,packet.getLength());//very important !!
- // System.out.println(message.length());
- inceAr.setText("正在接受的內容: \n"+message);
- inced.append(message+"\n");
- if(b==true){
- break;
- }
- }
- }
- public void actionPerformed(ActionEvent e){
- Object object=e.getSource();
- if(object==ince){
- //If this thread is already on the state "run", do nothing.
- if(!thread.isAlive()){
- thread=new Thread(this);
- thread.start();
- ince.setBackground(Color.red);
- stop.setBackground(Color.yellow);
- b=false;
- }
- }
- if(object==stop){
- ince.setBackground(Color.yellow);
- stop.setBackground(Color.red);
- b=true;
- }
- }
- public static void main(String[] args){
- @SuppressWarnings("unused")
- Receive rec=new Receive();
- // rec.setSize(460, 200);//提供了額外設置窗體大小的方式
- }
- }
這上面的程序運用了很多JAVA的核心技術以及很多需要注意的地方,可以堪稱一個JAVA的精髓例子,記錄下來以便以後查閱。