1)UDP协议概述
2)UDP服务器与客户端程序
服务器端:
String info ="......"
//将信息封装成数据包
byte[] bytes = info.getBytes();
//客户端在5000端口监听
DatagramPacket dp = new DatagramPacket(bytes,0,bytes.length,InetAddress.getByName("localhost"),5000);
//服务器的端口
DatagramSocket server = new DatagramSocket(3000);
//发送数据包
server.send(dp);
server.close();
客户端:
//接收内容
byte b[] new byte[1024];
//接收内容
DatagramPacket dp = new DatagramPacket(b,b.length);
//客户端在5000端口等待
DatagramSocket client = new DatagramSocket(5000);
//接收内容
client.receive(dp);
System.out.println(new String(dp.getData(),0,dp.getLength()));
client.close();
package com.vince;
import java.io.IOException;
import java.net.*;
public class UDPServiceDemp {
public static void main(String[] args) {
String info = "碧瑶很漂亮,我很喜欢!!!!!!";
//将信息封装成数据包
byte[] bytes = info.getBytes();
try {
/**
* 封装一个数据包
* offset:分组数据偏移量
* length:分组数据长度
* InetAddress:目的地址
* port:目的端口号
*/
DatagramPacket dp = new DatagramPacket(
bytes,
0,
bytes.length,
InetAddress.getByName("127.0.0.1"),
8000);
//本程序的端口
DatagramSocket socket = new DatagramSocket(9000);
//发送数据包
socket.send(dp);
socket.close();
}catch (UnknownHostException e){
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.vince;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UDPClientDemo {
public static void main(String[] args) {
//接收内容
byte[] bytes = new byte[1024];
DatagramPacket dp = new DatagramPacket(bytes,bytes.length);
try {
//客户端在8000端口等待
DatagramSocket socket = new DatagramSocket(8000);
System.out.println("正在接收数据中......");
//接收数据
socket.receive(dp);
String s = new String(dp.getData(),0,dp.getLength());
System.out.println(s);
socket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}