一、需求描述
实现UDP的通信
1.1 一发一收
1.1.1 ClientTest1
package com.itheima.udp;
import java.net.*;
import static java.net.InetAddress.*;
//完成udp通信快速入门,实现一收一发
public class ClientTest1 {
public static void main(String[] args) throws Exception {
//创建客户端对象
DatagramSocket socket = new DatagramSocket();
//创建数据包对象封装要发出去的数据
byte[] bytes = "我是快乐的客户端,我负责发送数据".getBytes();
//4个参数代表:
//1、要发送的数据
//2、要发送的数据大小(字节数)
//3、服务端的IP
//4、服务端程序的端口号
DatagramPacket packet = new DatagramPacket(bytes,bytes.length, getLocalHost(),6666);
//开始发送数据包的数据出去
socket.send(packet);
System.out.println("客户端数据发送完毕!!!");
//发送后关闭通信管道
socket.close();
}
}
1.1.2 ServerTest1
package com.itheima.udp;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class ServerTest1 {
public static void main(String[] args) throws Exception {
System.out.println("-----服务端启动----------");
//创建一个服务端对象,用来接收数据。需要注册端口
DatagramSocket socket = new DatagramSocket(6666);
//创建一个数据包对象,用于接收数据
byte[] buffer = new byte[1024 * 64];
DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
//开始接受数据
socket.receive(packet);
//获取本次数据包接收了多少数据
int len = packet.getLength();
String res = new String(buffer,0,len);
System.out.println(res);
//获取客户端的IP地址和端口号
System.out.println(packet.getAddress().getHostAddress());
System.out.println(packet.getPort());
//释放资源
socket.close();
}
}
1.1.3 运行结果
1.2 多发多收
1.2.1 Client
package com.itheima.udp2;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws Exception {
//创建客户端对象
DatagramSocket socket = new DatagramSocket();
Scanner sc = new Scanner(System.in);
while (true){
//让用户输入要发送的消息
System.out.println("请说:");
String msg = sc.nextLine();
//输入exit时退出
if ("exit".equals(msg)) {
System.out.println("欢迎下次光临!退出成功!!!");
//关闭通道
socket.close();
break;
}
byte[] bytes = msg.getBytes();
//创建发送数据的数据包
DatagramPacket packet = new DatagramPacket(bytes,bytes.length,InetAddress.getLocalHost(),6666);
//开始发送数据
socket.send(packet);
}
//客户端数据发送完毕
System.out.println("客户端数据发送完毕");
}
}
1.2.2 Server
package com.itheima.udp2;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Server {
public static void main(String[] args) throws Exception {
System.out.println("-----服务端启动----------");
//创建一个服务端对象,用来接收数据。需要注册端口
DatagramSocket socket = new DatagramSocket(6666);
//创建一个数据包对象,用于接收数据
byte[] buffer = new byte[1024 * 64];
DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
while (true) {
//开始接受数据
socket.receive(packet);
//获取本次数据包接收了多少数据
int len = packet.getLength();
String res = new String(buffer,0,len);
System.out.println(res);
//获取客户端的IP地址和端口号
System.out.println(packet.getAddress().getHostAddress());
System.out.println(packet.getPort());
System.out.println("----------------------");
}
}
}
1.2.3 运行结果