62,634
社区成员




import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class UdpSender {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket(8888);
Scanner scanner = new Scanner(System.in);
System.out.println("输入要发送的信息:");
while(true){
String msg = scanner.nextLine();
byte[] buf = msg.getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length,
InetAddress.getByName("localhost"), 10000);
ds.send(dp);
System.out.printf("%s sent!", msg);
if("quit".equalsIgnoreCase(msg))
break;
}
ds.close();
}
}
接收端:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpReceiver {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket(10000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
String data = null;
while(!"quit".equalsIgnoreCase(data)){
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
data = new String(dp.getData(), 0, dp.getLength());
System.out.println(ip+"::"+data);
}
System.out.println("byebye");
ds.close();
}
}