UDP广播 java (netbeans)

原创 2006年05月25日 22:39:00

客户端:

/*
 * ReceiveFrame.java
 *
 * Created on 2006年5月25日, 上午9:28
 */

package broadcastreceive;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;

/**
 *
 * @author  Terry
 */
public class ReceiveFrame extends javax.swing.JFrame implements Runnable
{
   
    /** Creates new form ReceiveFrame */
    public ReceiveFrame()
    {
        initComponents();
        thread = new Thread(this);
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" 生成的代码 ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jScrollPaneforText = new javax.swing.JScrollPane();
        jTextAreaInfo = new javax.swing.JTextArea();
        jButtonReceive = new javax.swing.JButton();
        jButtonStop = new javax.swing.JButton();
        jLabelInfo = new javax.swing.JLabel();
        jLabelIp = new javax.swing.JLabel();
        jTextFieldIp = new javax.swing.JTextField();
        jTextFieldPort = new javax.swing.JTextField();
        jLabelPort = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("/u5e7f/u64ad/u5ba2/u6237/u7aef");
        jTextAreaInfo.setColumns(20);
        jTextAreaInfo.setRows(5);
        jScrollPaneforText.setViewportView(jTextAreaInfo);

        jButtonReceive.setText("/u63a5/u6536/u5e7f/u64ad");
        jButtonReceive.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonReceiveActionPerformed(evt);
            }
        });

        jButtonStop.setText("/u505c/u6b62/u63a5/u53d7");
        jButtonStop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonStopActionPerformed(evt);
            }
        });

        jLabelInfo.setText("/u63a5/u53d7/u5230/u7684/u5e7f/u64ad/u4fe1/u606f");

        jLabelIp.setText("/u5e7f/u64ad/u5730/u5740");

        jTextFieldIp.setText("239.255.8.9");

        jTextFieldPort.setText("5858");

        jLabelPort.setText("/u7aef/u53e3");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(19, 19, 19)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabelInfo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 129, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(jScrollPaneforText, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 303, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(layout.createSequentialGroup()
                                .add(jLabelIp, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 58, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(jTextFieldIp, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 191, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .add(jLabelPort)))
                        .add(18, 18, 18)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jTextFieldPort, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 73, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                .add(jButtonStop)
                                .add(jButtonReceive)))))
                .addContainerGap(19, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(32, 32, 32)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabelIp, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jTextFieldIp, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 22, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabelPort)
                    .add(jTextFieldPort, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 33, Short.MAX_VALUE)
                .add(jLabelInfo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(jButtonReceive, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 35, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(88, 88, 88)
                        .add(jButtonStop, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 35, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(29, 29, 29))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(jScrollPaneforText, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 223, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonStopActionPerformed
// TODO 将在此处添加您的处理代码:
        stop = true;
    }//GEN-LAST:event_jButtonStopActionPerformed
    //接受按钮事件
    private void jButtonReceiveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonReceiveActionPerformed
// TODO 将在此处添加您的处理代码:
        try
        {
            port = Integer.parseInt(jTextFieldPort.getText());     //得到端口号
            group = InetAddress.getByName(jTextFieldIp.getText()); //得到组播地址
            socket = new MulticastSocket(port);
            socket.joinGroup(group);                                //加入组播组
        }
        catch(Exception e)
        {
        }
        if (!(thread.isAlive()))
        {
            thread = new Thread(this);
            stop = false;
        }
        try
        {
            thread.start();
        }
        catch(Exception ee){}
    }//GEN-LAST:event_jButtonReceiveActionPerformed
   
    /**
     * @param args the command line arguments
     */
    public void run()
   {
        while(true)
 {
  byte data[] = new byte[8192];
  DatagramPacket packet = null;
  packet=new DatagramPacket(data,data.length,group,port);
  try
  {
   socket.receive(packet);
   String message = new String(packet.getData(),0,packet.getLength());
   jTextAreaInfo.append("/n"+message);
   jTextAreaInfo.setCaretPosition(jTextAreaInfo.getText().length());
  }
  catch(Exception e){}
  if (stop == true)
  {
   break;
  }
 }
   }
    // 变量声明 - 不进行修改//GEN-BEGIN:variables
    private javax.swing.JButton jButtonReceive;
    private javax.swing.JButton jButtonStop;
    private javax.swing.JLabel jLabelInfo;
    private javax.swing.JLabel jLabelIp;
    private javax.swing.JLabel jLabelPort;
    private javax.swing.JScrollPane jScrollPaneforText;
    private javax.swing.JTextArea jTextAreaInfo;
    private javax.swing.JTextField jTextFieldIp;
    private javax.swing.JTextField jTextFieldPort;
    // 变量声明结束//GEN-END:variables
    //自己声明的变量
    int port;                      //组播的端口
    InetAddress group;             //组播地址
    MulticastSocket socket;        //多点组播套接字
    Thread thread;                 //负责接受的线程
    boolean stop;
}

服务器端:

/*
 * SendFrame.java
 *
 * Created on 2006年5月24日, 下午4:28
 */

package netbroadcasting;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.net.*;
import java.net.DatagramSocket;
import java.lang.*;


/**
 *
 * @author Terry
 */
public class SendFrame extends javax.swing.JFrame
{
   
    /** Creates new form SendFrame */
    public SendFrame() //构造方法
    {
        initComponents();                    //制造窗体的方法
        setValue();                           //设置各个变量的值
        InetAddress group=null;               //设置组播放组
        MulticastSocket socket=null;          //多点广播套接字
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" 生成的代码 ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jDialogError = new javax.swing.JDialog();
        jTextFieldIPadderss = new javax.swing.JTextField();
        jLabelIp = new javax.swing.JLabel();
        jLabelInfo = new javax.swing.JLabel();
        jScrollPaneContainer = new javax.swing.JScrollPane();
        jTextAreaSendInfo = new javax.swing.JTextArea();
        jButtonSend = new javax.swing.JButton();
        jLabePort = new javax.swing.JLabel();
        jTextFieldPort = new javax.swing.JTextField();

        jDialogError.setTitle("/u8f93/u5165/u9519/u8bef");
        org.jdesktop.layout.GroupLayout jDialogErrorLayout = new org.jdesktop.layout.GroupLayout(jDialogError.getContentPane());
        jDialogError.getContentPane().setLayout(jDialogErrorLayout);
        jDialogErrorLayout.setHorizontalGroup(
            jDialogErrorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 400, Short.MAX_VALUE)
        );
        jDialogErrorLayout.setVerticalGroup(
            jDialogErrorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 300, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("/u5e7f/u64ad/u4e3b/u673a");
        jTextFieldIPadderss.setText("239.255.8.9");
        jTextFieldIPadderss.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldIPadderssActionPerformed(evt);
            }
        });

        jLabelIp.setText("/u4e3b/u673aIP");

        jLabelInfo.setText("/u8f93/u5165/u8981/u53d1/u9001/u7684/u4fe1/u606f");

        jTextAreaSendInfo.setColumns(20);
        jTextAreaSendInfo.setRows(5);
        jScrollPaneContainer.setViewportView(jTextAreaSendInfo);

        jButtonSend.setText("/u53d1/u9001/u6d88/u606f");
        jButtonSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSendActionPerformed(evt);
            }
        });

        jLabePort.setText("/u7aef/u53e3");

        jTextFieldPort.setText("5858");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(28, 28, 28)
                .add(jLabelIp)
                .add(32, 32, 32)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPaneContainer)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jLabelInfo)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                        .add(jTextFieldIPadderss, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 151, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(jLabePort)
                        .add(19, 19, 19)))
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jTextFieldPort, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButtonSend)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(48, 48, 48)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextFieldIPadderss, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 29, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabePort)
                    .add(jTextFieldPort, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 28, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabelIp, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 32, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jLabelInfo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 27, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jScrollPaneContainer, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 128, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .add(144, 144, 144)
                        .add(jButtonSend)))
                .addContainerGap(42, Short.MAX_VALUE))
        );

        layout.linkSize(new java.awt.Component[] {jLabePort, jLabelIp, jTextFieldIPadderss, jTextFieldPort}, org.jdesktop.layout.GroupLayout.VERTICAL);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextFieldIPadderssActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldIPadderssActionPerformed
// TODO 将在此处添加您的处理代码:
    }//GEN-LAST:event_jTextFieldIPadderssActionPerformed
    public void setValue()
    {
        saveInfo = new String("");
        saveIp = new String("");
    }   
//按钮事件
    private void jButtonSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSendActionPerformed
// TODO 将在此处添加您的处理代码:
        saveInfo = jTextAreaSendInfo.getText(); 
        saveIp = jTextFieldIPadderss.getText();
        port = Integer.parseInt(jTextFieldPort.getText());    //得到端口号
        try
        {
            group = InetAddress.getByName(saveIp);
            socket = new MulticastSocket(port);              //设置端口
            socket.setTimeToLive(0);                         //多点广播套接字数据报为本地网络地址
            socket.joinGroup(group);                         //加入广播组
        }
        catch(Exception e){}
        try
        {
            DatagramPacket packet = null;   //等待广播的数据报
            byte data[] = saveInfo.getBytes();
            packet = new DatagramPacket(data,data.length,group,port);
            socket.send(packet);            //发送数据报          
         }
         catch(Exception e){}
    }//GEN-LAST:event_jButtonSendActionPerformed
   
    /**
     * @param args the command line arguments
     */

   
    // 变量声明 - 不进行修改//GEN-BEGIN:variables
    private javax.swing.JButton jButtonSend;
    private javax.swing.JDialog jDialogError;
    private javax.swing.JLabel jLabePort;
    private javax.swing.JLabel jLabelInfo;
    private javax.swing.JLabel jLabelIp;
    private javax.swing.JScrollPane jScrollPaneContainer;
    private javax.swing.JTextArea jTextAreaSendInfo;
    private javax.swing.JTextField jTextFieldIPadderss;
    private javax.swing.JTextField jTextFieldPort;
    // 变量声明结束//GEN-END:variables
    String saveInfo;                 //用于保存发送信息的变量
    String saveIp;                   //保存网段IP地址的变量
    int port;
    InetAddress group;               //设置组播放组
    MulticastSocket socket;          //多点广播套接字
}

 

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

java接听UDP广播

JAVA基于UDP的多点广播数据报技术的一个实现例子

com.han.Weather This is a UDP network program. The following presents a multicast datagram prog...

java udp 广播及socket通讯

udp 是一种网络通信协议,不需要客户端和服务器端建立连接即可进行通讯功能。相对于Tcp协议它有着tcp用很多优点,例如广播功能。udp的广播功能可以指定特定网段进行广播内容,而无需知道接收者是谁,只...

Java笔记(9)-网络编程、URL、InetAddress、套接字、Socket、ServerSocket、多线程、UDP、广播数据包、远程调用

不必说碧绿的菜畦,光滑的石井栏,高大的皂荚树,紫红的桑葚;也不必说鸣蝉在树叶里长吟,肥胖的黄蜂伏在菜花上,轻捷的叫天子(云雀)忽然从草间直窜向云霄里去了。 Java网络编程 URL 类 InetAd...

Java UDP 单播、多播(组播)、广播、任播(未实现)

单播、组播、广播、任播的定义 单播(unicast): 是指封包在计算机网络的传输中,目的地址为单一目标的一种传输方式。它是现今网络应用最为广泛,通常所使用的网络协议或服务大多采用单播传输,例如...

java UDP实现局域网广播

使用UDP协议进行信息的传输之前不需要建议连接。换句话说就是客户端向服务器发送信息,客户端只需要给出服务器的ip地址和端口号,然后将信息封装到一个待发送的报文中并且发送出去。至于服务器端是否存在,或者...

Java网络编程笔记--实现UDP广播发送与接收

Java网络编程笔记启用UDP广播发送下通信编程//发送端代码 import java.io.IOException; import java.net.DatagramPacket; import j...

C# UDP通信 多路广播

内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)