UDP 发送消息
public class UDPreceive {
public static void main(String[] args) throws Exception {
//自己的端口
DatagramSocket socket= new DatagramSocket(9901);
try {
while(true){
//准备接包
byte[] butter=new byte[1024];
DatagramPacket packet=new DatagramPacket(butter, 0,butter.length);
socket.receive(packet);
//拆包 获得信息
byte [] data =packet.getData();
String receivedata=new String(data,0,data.length-1);
if(receivedata.equals("Bye")){
socket.close();
System.out.println("关闭了接口");
break;
}
else{
System.out.println("消息:"+receivedata);
}
}
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally {
//先开后关
socket.close();
System.out.println("关闭了接口");
}
}
}
public class UDPSender {
public static void main(String[] args) throws Exception {
// 自己的 端口号
DatagramSocket socket=new DatagramSocket(2010);
//控制台输入
BufferedReader buffere=new BufferedReader(new InputStreamReader(System.in));
//准备数据
while(true){
//打包
String string=buffere.readLine();
byte [] data=string.getBytes();
//填写地址
//InetSocketAddress socketIP=;
//包上车
DatagramPacket packet = new DatagramPacket(data,0,data.length,new InetSocketAddress("localhost",9901));
//发车
socket.send(packet);
if(string.equals("Bye")){
break;
}
}
socket.close();
System.out.println("关闭了接口");
}
}
当从 UDPSender类中输入 “Bye”时, UDPreceive类中的 if语句出现异常,使得UDPreceive不能正常退出。