UDP协议,简单的说就是,发信息。
不管对方有没有收到。
发送端:
import java.net.*;
public class UDP_Send {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
byte[] buf = "我是王二萌remoo,你也可以叫我remoo".getBytes();
int length = buf.length;
InetAddress ip = InetAddress.getByName("localhost");
int port = 8899;
DatagramPacket dp = new DatagramPacket(buf,length,ip,port);
ds.send(dp);
ds.close();
}
}
接收端:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDP_Receive {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(8899);//如果要监听,则在构造的时候就要指定需要监听的端口。
byte[] buf = new byte[1024];
int length = buf.length;
DatagramPacket dp = new DatagramPacket(buf,length);
ds.receive(dp);
String str = new String(dp.getData(),0,dp.getLength());
System.out.println(str);
ds.close();
}
}
先运行接收端,再运行发送端。
成功接收信息!
如何持续发送和接收数据呢?
发送端:
import java.net.*;
import java.util.Scanner;
public class UDP_Send {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
Scanner sc = new Scanner(System.in);
while(true){
// byte[] buf = "我是王二萌remoo,你也可以叫我remoo".getBytes();
byte[] buf = sc.next().getBytes();
int length = buf.length;
InetAddress ip = InetAddress.getByName("localhost");
int port = 8899;
DatagramPacket dp = new DatagramPacket(buf,length,ip,port);
ds.send(dp);
}
//ds.close();
}
}
接收端:
import java.net.*;
public class UDP_Receive {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(8899);//如果要监听,则在构造的时候就要指定需要监听的端口。
while(true){
byte[] buf = new byte[1024];
int length = buf.length;
DatagramPacket dp = new DatagramPacket(buf,length);
ds.receive(dp);
String str = new String(dp.getData(),0,dp.getLength());
InetAddress ip = dp.getAddress();
System.out.println("来自:"+dp.getSocketAddress()+"的信息\n"+str+"\n-----------");
}
//ds.close();
}
}
运行效果:
设置当用户输入“end”的时候终止发送
发送端:使用str.equal()就可以啦。
import java.net.*;
import java.util.Scanner;
public class UDP_Send {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
Scanner sc = new Scanner(System.in);
while(true){
// byte[] buf = "我是王二萌remoo,你也可以叫我remoo".getBytes();
String str = sc.next();
if(str.equals("end"))break;
byte[] buf = str.getBytes();
int length = buf.length;
InetAddress ip = InetAddress.getByName("localhost");
int port = 8899;
DatagramPacket dp = new DatagramPacket(buf,length,ip,port);
ds.send(dp);
}
ds.close();
}
}
当用户输入end的时候,退出发送端。大家也可以通过输入某些文字让接收端关闭!请大家自行探索。