文章目录
UDP简介
UDP(User Datagram Protocol)
java
DatagramSocket 用于创建客户端、服务端
DatagramSocket() :创建客户端的Socket对象,系统随机分配一个端口
DatagramSocket(int port) : 创建服务端的Socket对象,指定端口号
DatagramPacket(byte buf[], int length,InetAddress address, int port)
创建发出去的数据包
参数解释:
byte buf[]:字节数组,用于接收数据
int length :数据的长度
InetAddress address 网址对象
int port 端口号
DatagramPacket(byte buf[], int length)
创建用来接收的数据包
方法:
java
send(DatagramPacket p) //发数据
receive(DatagramPacket p) //接收数据
一发一收
要先启动服务端再启动客户端。
客户端:
java
public class Client {
public static void main(String[] args) throws Exception {
//创建客户端对象
DatagramSocket socket = new DatagramSocket();
/* public DatagramPacket(byte buf[], int length,
InetAddress address, int port) */
byte[] bytes = "客户端发送给了一个数据包".getBytes();
DatagramPacket packet = new DatagramPacket(bytes,bytes.length, InetAddress.getLocalHost(),6666);
socket.send(packet);
System.out.println("客户端数据发送完毕");
socket.close();
//记得关闭,不然占用资源。
}
}
服务端:
java
public class Server {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(6666);
System.out.println("服务端启动");
//创建一个数据包对象,用于接受数据
byte[] buffer = new byte[1024 * 64];//数据包最大为64k
DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
socket.receive(packet);
int len = packet.getLength();
String rs = new String(buffer,0,len);
System.out.println(rs);
System.out.println("客户端的IP:"+packet.getAddress().getHostAddress());
System.out.println("客户端的端口:"+packet.getPort());
socket.close();
}
}
多发多收
相比一收一发改进的地方:
- 实现多次发送自定义信息
- 输入stop 时候退出
实现多开
客户端:
java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws Exception {
//创建客户端对象
DatagramSocket socket = new DatagramSocket();
/* public DatagramPacket(byte buf[], int length,
InetAddress address, int port) */
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入数据:");
String msg = sc.nextLine();
if (msg.equals("stop")) {
break;
}
byte[] bytes = msg.getBytes();
DatagramPacket packet = new DatagramPacket(bytes,bytes.length, InetAddress.getLocalHost(),6666);
socket.send(packet);
}
System.out.println("感谢使用!!!");
socket.close();
}
}
服务端
服务端一般是不关闭的。
java
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class Server {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(6666);
System.out.println("服务端启动");
while (true) {
//创建一个数据包对象,用于接受数据
byte[] buffer = new byte[1024 * 64];
DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
socket.receive(packet);
int len = packet.getLength();
String rs = new String(buffer,0,len);
System.out.println(rs);
System.out.println("客户端的IP:"+packet.getAddress().getHostAddress());
System.out.println("客户端的端口:"+packet.getPort());
}
// socket.close();
}
}