package com.ece.manager.web.deviceFB;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class TestServer {
public static void main(String[] args) {
int port = 9090;//开启监听的端口
DatagramSocket ds = null;
DatagramPacket dp = null;
byte[] buf = new byte[1024];//存储发来的消息
StringBuffer sbuf = new StringBuffer();
try {
//绑定端口的
ds = new DatagramSocket(port);
dp = new DatagramPacket(buf, buf.length);
System.out.println("监听广播端口打开:");
ds.receive(dp);
ds.close();
int i;
for(i=0;i<1024;i++){
if(buf[i] == 0){
break;
}
sbuf.append((char) buf[i]);
}
System.out.println("收到广播消息:" + sbuf.toString());
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.ece.manager.web.deviceFB;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class Test {
public static void main(String[] args) {
// 广播的实现 :由客户端发出广播,服务器端接收
String host = "255.255.255.255";//广播地址
int port = 9090;//广播的目的端口
String message = "test";//用于发送的字符串
try {
InetAddress adds = InetAddress.getByName(host);
DatagramSocket ds = new DatagramSocket();
DatagramPacket dp = new DatagramPacket(message.getBytes(),
message.length(), adds, port);
ds.send(dp);
ds.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}