import java.net.*;
import java.io.*;
public class TestUDPServer {
public static void main(String[] args) throws Exception {
byte [] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
DatagramSocket ds = new DatagramSocket(5678);
ByteArrayInputStream bais = new ByteArrayInputStream(buf);
while(true) {
DataInputStream dis = new DataInputStream(bais);
ds.receive(dp);//阻塞式的
//System.out.println(new String(buf, 0, dp.getLength()));
System.out.println(dis.readLong());
}
}
}
import java.net.*;
import java.io.*;
public class TestUDPClient {
public static void main(String[] args) throws Exception{
//向服务器端传一个long类型数字
long n = 10000;
ByteArrayOutputStream baos =
new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeLong(n);
byte [] buf = baos.toByteArray();
//byte [] buf = (new String("hello")).getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress("127.0.0.1",5678));
DatagramSocket ds = new DatagramSocket(9999);
ds.send(dp);
ds.close();
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步