UDP网络程序设计思路

UDP网络程序设计思路

	相当于一个广场上通知事情的大喇叭,在宣传,但却不一定保证每个人都能听到消息;

主要掌握的构造方法

数据包:
DatagramPacket(byre[] buf ,int length,InetAddtess address,int port)
构造方法 包数据 包长度 目的地址 目的端口

数据包套接字:
DatagramSocket(int port,InetAddress addr)
构造方法 端口 ip地址

子类:
MulticastSocket extends DatagramSocket
		joinGroup(InetAddress) //加入广播组;
		leaveGroup(InetAddress)//离开广播组;

构建思路

在这里插入图片描述

程序示例

udpserver

package udpserver;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class server extends Thread{//继承线程类,让不断发广播
	int port = 9898;//端口
	InetAddress group;//广播组地址
	MulticastSocket socket;//创建多播数据包套接字
	
	//进行套接字实例化
	public server() {
		
		//这里的地址范围224.0.0.0~239.255.255.255
		try {
			group=InetAddress.getByName("224.255.10.0");//指定广播组地址
			socket = new MulticastSocket(port);//实例化多播数据包套接字
			socket.joinGroup(group);//加入广播组
			
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public void run() {
		while(true) {
			DatagramPacket packet;
			Date date = new Date();
			
			SimpleDateFormat  sf = new SimpleDateFormat("HH:mm:ss");//定义时间格式
			String message = "["+sf.format(date)+"]今天天气晴朗,你好啊!";
			
			byte data[] = message.getBytes();
			packet = new DatagramPacket(data,data.length,group,port);//创建数据包
			
			try {
				socket.send(packet);//发送出去数据包
				
				Thread.sleep(1000);
				System.out.println(message);
				
			} catch (IOException | InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
	}
	
	
	
	
	public static void main(String[] args) {
		server send = new server();
		send.start();
		
	
	}

}

udpclient

package udpclient;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;//动作 监听
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

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

/**
 * 
 * @author Administrator
 * 这里创建clent 用于接收服务端UDP 广播情况
 */
public class client extends JFrame implements Runnable,ActionListener{
	JButton ince = new JButton("start reseive:");//开始接收 按钮
	JButton stop = new JButton("stop receive!");//停止接收按钮
	
	JTextArea inceAre = new JTextArea(10,10);//显示接收广播提示
	JTextArea inced = new JTextArea(10,10);//显示接收的广播
	
	Thread thread;//创建Thread 对象,用来新开线程执行广播接收操作
	boolean getMessage = true;//是否接收广播
	
	int port = 9898;//端口
	InetAddress group;//广播组地址
	MulticastSocket socket;//创建多播数据包套接字
	

	
	//构造方法
	public  client() {
		super("broadcast");//设置窗体标题
		
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//设置窗体关闭方法
		inceAre.setForeground(Color.BLUE);//指定提示文本域中文字颜色
		
		JPanel north = new JPanel();//创建JPane对象
		north.add(ince);//将按钮添加到north上
		north.add(stop);
		add(north,BorderLayout.NORTH);//将north设置在窗体的上部
		
		JPanel center = new JPanel();//创建面板对象center
		center.setLayout(new GridLayout(1,2));//设置面板布局
		center.add(inceAre);//将文本添加到面板上
		
		final JScrollPane scrollPane = new JScrollPane();
		center.add(scrollPane);
		scrollPane.setViewportView(inced);
		add(center,BorderLayout.CENTER);//设置面板布局
		
		thread = new Thread(this);//创建线程运行自己的run方法
		
		//添加监听
		ince.addActionListener(this);
		stop.addActionListener(this);
		
		validate();//重新验证容器苗中的组件,刷新组件
		setBounds(100, 50, 360, 380);//设置布局
		setVisible(true);//将窗体设置为显示状态
		
		try {
			group=InetAddress.getByName("224.255.10.0");//指定广播组地址
			socket = new MulticastSocket(port);//实例化多播数据包套接字
			socket.joinGroup(group);//加入广播组
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
	}
	
	
	/**
	 * 
	 * @param args  主方法
	 */
	public static void main(String[] args) {
		
		client recve = new client();//创建本类对象
		recve.setSize(460, 300);//设置窗体大小
		
		
	}


	
	//创建两个抽象方法
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getSource() == ince) {
			ince.setBackground(Color.red);
			stop.setBackground(Color.yellow);
			
			if(!thread.isAlive()) {//如果线程不是存活的状态
				thread = new Thread(this);
				getMessage = true;
			}
			thread.start();
		}
		
		if(e.getSource()==stop) {
			ince.setBackground(Color.yellow);
			stop.setBackground(Color.red);
			getMessage = false;
			
		}
	}

	public void run() {
		while(getMessage) {
			DatagramPacket packet;
			byte data[] = new byte[1024];
			packet = new DatagramPacket(data,data.length,group,port);
	
			try {
					socket.receive(packet);//读取数据包
					String message  = new String(packet.getData(),0,packet.getLength());//从数据包中读取数据
					inceAre.setText("receiving data:"+message); 
					inced.append(message+"\n");

					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
		}
		
			
	}

}

示例结果展示

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值