模拟服务端接收方代码,先运行客户端
public class DoubleMyServer {
public static void main(String[] args) {
try {
DatagramSocket server = new DatagramSocket(8888);
byte[]container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container,container.length);
server.receive(packet);
double num =convert(packet.getData());
System.out.println(num);
//释放资源
server.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 接收方将数据转化为double
* @param data
* @return
*/
public static double convert(byte[]data){
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));
double num = 0;
try {
num = dis.readDouble();
} catch (IOException e) {
e.printStackTrace();
}
return num;
}
}
模拟客户端接收方代码
public class DoubleMyClient {
public static void main(String[] args) {
try {
DatagramSocket client =new DatagramSocket(6666);
double num =58.12;
byte[]data =convert(num);
DatagramPacket packet = new DatagramPacket(data,data.length,new InetSocketAddress("localhost",8888));
client.send(packet);
client.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 将double数据转换成字节数组输出流
* @param dob
* @return
*/
public static byte[] convert(double num){
byte[]data=null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeDouble(num);
dos.flush();
data=bos.toByteArray();
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
}
基于UDP通信的基础Demo
最新推荐文章于 2024-03-19 20:35:05 发布