首页 > 代码库 > UDP Server

UDP Server

//UDP服务器端程序,可以接受广播,不可接受多播,多播需要join播地址
@Override
public void run() {
while (true) {

try {
DatagramSocket server = new DatagramSocket(5050);
byte[] recvBuf = new byte[1024];
DatagramPacket recvPacket = new DatagramPacket(recvBuf, recvBuf.length);

while (true) {
//接收数据
server.receive(recvPacket);
String recvStr = new String(recvPacket.getData(), 0, recvPacket.getLength());
iListenerResutlt.onRecieve(recvStr);
//回复数据
int port = recvPacket.getPort();
InetAddress addr = recvPacket.getAddress();
String sendStr =recvStr;
byte[] sendBuf;
sendBuf = sendStr.getBytes("gbk");
DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length, addr, port);
server.send(sendPacket);

}
} catch (Exception e) {
e.printStackTrace();
}
}
}

UDP Server