***话不多说直接上代码***
***未打注释的地方全靠自己领悟***
1.客户端
public class Datagramkehu {
public static void main(String[] args) {
//初始化DataDatagramSocket 对象
DatagramSocket ds=null;
//初始化DatagramPacket 对象
DatagramPacket dp;
Scanner sc=new Scanner(System.in);
try {
System.out.println("客户端开启");
//实例化
ds=new DatagramSocket();
//输入字符串并转为字符数组
byte[] buf = sc.next().getBytes();
//实例化
dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("127.0.0.1"), 2033);
ds.send(dp);
ds.close();
ds=new DatagramSocket(2244);
byte []b=new byte[buf.length];
dp=new DatagramPacket(b,b.length);
ds.receive(dp);
String rs=new String(dp.getData());
System.out.println(rs);
} catch (IOException e) {
e.printStackTrace();
}finally {
assert ds != null;
ds.close();
}
}
}
2.服务端
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Datagramfuwu {
public static void main(String[] args) {
DatagramSocket ds=null;
DatagramPacket dp;
try {
System.out.println("服务器开启");
ds=new DatagramSocket(2033);
byte []b=new byte[1024];
dp=new DatagramPacket(b,b.length);
ds.receive(dp);
String rs=new String(dp.getData());
System.out.println(dp.getAddress().getHostName()+":"+rs);
ds=new DatagramSocket();
rs=rs.trim();
byte []a=(rs.length()+"").getBytes();
ds=new DatagramSocket();
dp = new DatagramPacket(a, a.length, InetAddress.getByName("127.0.0.1"), 2244);
ds.send(dp);
} catch (IOException e) {
e.printStackTrace();
}
finally {
assert ds != null;
ds.close();
}
}
}