package j2se.core.net.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.util.Scanner;
/**
* 通过 UDP 发送数据的简单范例
*/
public class Sender {
public static void main(String[] args) throws IOException {
// 使用指定的端口,创建 数据报嵌套字(用于发送数据)
DatagramSocket socket = new DatagramSocket();
// 创建数据报发送目的地的地址对象
InetSocketAddress address = new InetSocketAddress("127.0.0.1", 1234);
// 接收用户输入
Scanner scanner = new Scanner(System.in);
while (true) {
String content = scanner.nextLine();
if (content.length() == 0)
break;
byte[] message = content.getBytes();
DatagramPacket packet = new DatagramPacket(message, message.length, address);
socket.send(packet);
}
socket.close();
}
}
package j2se.core.net.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.util.Scanner;
/**
* 通过 UDP 发送数据的简单范例
*/
public class Sender {
public static void main(String[] args) throws IOException {
// 使用指定的端口,创建 数据报嵌套字(用于发送数据)
DatagramSocket socket = new DatagramSocket();
// 创建数据报发送目的地的地址对象
InetSocketAddress address = new InetSocketAddress("127.0.0.1", 1234);
// 接收用户输入
Scanner scanner = new Scanner(System.in);
while (true) {
String content = scanner.nextLine();
if (content.length() == 0)
break;
byte[] message = content.getBytes();
DatagramPacket packet = new DatagramPacket(message, message.length, address);
socket.send(packet);
}
socket.close();
}
}
package j2se.core.net.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
/**
* 通过 UDP 接收数据的简单范例
*/
public class Receiver {
public static void main(String[] args) throws IOException {
// 使用指定的端口,创建 数据报嵌套字(用于接收数据)
DatagramSocket socket = new DatagramSocket(1234);
// 创建长度为 1024 个字节的数据报对象
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
while (true) {
socket.receive(packet);
byte[] data = packet.getData();
String s = new String(data, 0, packet.getLength());
System.out.println("接收到的内容:" + s);
if (s.equals("quit"))
break;
}
socket.close();
}
}