java下发报文_java报文的发送和接收 | 学步园
/*
* 發(fā)送端
*/
public void send() throws Exception {
System.out.println("send..............");
// 得到目標(biāo)機(jī)器的地址實(shí)例
InetAddress target = InetAddress.getByName("localhost");
// 從8888端口發(fā)送數(shù)據(jù)報(bào)
DatagramSocket ds = new DatagramSocket(8888);
String hello = "Hello, I am come in!";
// 將數(shù)據(jù)轉(zhuǎn)換成Byte類型
byte [] buf = hello.getBytes();
// 將BUF緩沖區(qū)中的數(shù)據(jù)打包,目標(biāo)端口為8889
DatagramPacket op = new DatagramPacket(buf, buf.length, target, 8889);
// 發(fā)送
ds.send(op);
ds.close();
System.out.println("send end." + target.getHostAddress());
}
/*
* 接收端
*/
public void receive() throws Exception {
System.out.println("receive........");
byte [] buf = new byte [1000];
// 監(jiān)視8889端口
DatagramSocket ds = new DatagramSocket(8889);
// 創(chuàng)建接收數(shù)據(jù)報(bào)的實(shí)例
DatagramPacket ip = new DatagramPacket(buf, buf.length);
while (true ) {
// 將收到的數(shù)據(jù)報(bào)裝入IP中
ds.receive(ip);
System.out.println(new String(buf));
}
}
總結(jié)
以上是生活随笔為你收集整理的java下发报文_java报文的发送和接收 | 学步园的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java中this.value_java
- 下一篇: m5310模组数据上传至onenet_硬