UDP(用户数据报协议)是网络消息传输的另一种形式。基于UDP的通信和基于TCP的通信不同,基于UDP的信息传递更快,但不提供可靠的保证。使用UDP传递数据时,用户无法知道数据能否正确地到达主机,也不能确定到达目的地的顺序是否余发送的顺序相同。虽然UDP时一种不可靠协议,但如果需要较快地传输信息,并能容忍效小的错误,可以考虑使用UDP。
基于UDP通信的几把模式如下:
1、将数据打包,然后将数据包发往目的地
2、接收别人发来的数据包,然后查看数据包
UDP程序的步骤如下:
发送数据包:
1、使用DatagramSocket()创建一个数据包套接字
2、使用DatagramPacket(byte[] buf,int offset,int length,InetAddress address,int port)创建要发送的数据包
3、使用DatagramSocket类的send()方法发送数据包
接收数据包:
1、使用DatagramSocket(int port)创建数据包套接字,绑定到指定的端口
2、使用DatagramPacket(byte[] buf,int length)创建字节数组来接收数据包
3、使用DatagramPacket类的receive()方法接收UDP包
一、DatagramPacket类
java.net包的DatagramPacket类用来表示数据包,DatagramPacket类的构造函数有:
(1)DatagramPacket(byte[] buf,int length)
(2)DatagramPacket(byte[] buf,int offset,int length,InetAddress address,int port)
二、DatagramSocket类
java.net包中的DatagramSocket类用于表示发送和接收数据包的套接字,该类的构造函数有:
(1)DatagramSocket()
(2)DatagramSocket(int port)
(3)DatagramSocket(int port,InetAddress addr)
三、UDP程序设计
1、广播主机程序不断地向外发出信息
package test;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
public class Weather extends Thread{
String weather = "节目预报:LOLS11总决赛";
int port = 9899;
InetAddress iaddress = null;
MulticastSocket socket = null;
Weather(){
try {
iaddress = InetAddress.getByName("224.255.10.0");
socket = new MulticastSocket(port);
socket.setTimeToLive(1);
socket.joinGroup(iaddress);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void run() {
while(true) {
DatagramPacket packet = null;
byte data[] = weather.getBytes();
packet = new DatagramPacket(data, data.length,iaddress,port);
System.out.println(new String(data));
try {
socket.send(packet);
sleep(3000);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
public static void main(String args[]) {
Weather w = new Weather();
w.start();
}
}
输出结果如下:
接收广播程序:
package test;
import java.awt.BorderLayout;
import java.awt.Color;
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.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
public class Receive extends JFrame implements Runnable,ActionListener{
int port;
InetAddress group = null;
MulticastSocket socket = null;
JButton ince = new JButton("开始接受");
JButton stop = new JButton("停止接受");
JTextArea inceAr = new JTextArea(10,10);
JTextArea inced = new JTextArea(10,10);
Thread thread;
boolean b = false;
public Receive() {
super("广播数据报");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
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();
center.setLayout(new GridLayout(1,2));
center.add(inceAr);
center.add(inced);
add(center,BorderLayout.CENTER);
validate();
port = 9899;
try {
group = InetAddress.getByName("224.255.10.0");
socket = new MulticastSocket(port);
socket.joinGroup(group);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
setBounds(100,50,360,360);
setVisible(true);
}
public void run(){
while(true) {
byte data[] = new byte[1024];
DatagramPacket packet = null;
packet = new DatagramPacket(data, data.length,group,port);
try {
socket.receive(packet);
String message = new String(packet.getData(),0,packet.getLength());
inceAr.setText("正在接受的内容:\n"+message);
inced.append(message+"\n");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
if(b == true) {
break;
}
}
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==ince) {
ince.setBackground(Color.red);
stop.setBackground(Color.yellow);
if(!(thread.isAlive())) {
thread = new Thread(this);
}
thread.start();
b = false;
}
if(e.getSource()==stop) {
ince.setBackground(Color.yellow);
stop.setBackground(Color.red);
b = true;
}
}
public static void main(String args[]) {
Receive rec = new Receive();
rec.setSize(500,200);
}
}
输出结果如下: