그룹 방송 발견 서버의java 구현
[size=medium][color=green] 서버 발견 [/color][/size]
DiscoverServer
package com.gbcom.ccsv3.transport.multidiscover;
import org.apache.log4j.Logger;
/**
*
*
*
*
* @author syz
*
* @date 2015-6-26, 04:23:36
*
* @version v1.0.0
*
* @see com.gbcom.ccsv3.transport.multidiscover.DiscoverServer
*/
public class DiscoverServer {
private static final Logger LOGGER = Logger.getLogger(DiscoverServer.class);
private static class DiscoverServerHolder{
private static final DiscoverServer INSTANCE = new DiscoverServer();
}
/**
*
*
* @return DiscoverServer
*/
public static DiscoverServer getInstance() {
return DiscoverServerHolder.INSTANCE;
}
private boolean started = false;
private Receiver discover;
private DiscoverServer() {
discover = UdpDiscoverFactory.getMultiUdpDiscover();
}
/**
*
*/
public void on() {
started = true;
Thread t = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
discover.start();
} catch (Exception e) {
e.printStackTrace();
discover = null;
LOGGER.error("start discover server unknoe host", e);
started = false;
// maybe throws new exception.
}
}
});
t.start();
LOGGER.info("start discover server for device success!!!!");
}
/**
*
*/
public void off() {
if (discover != null) {
discover.stop();
}
started = false;
}
/**
*
*
* @return started
*/
public boolean isStarted() {
return started;
}
static class UdpDiscoverFactory {
/**
*
*
* @return Receiver
*/
public static Receiver getMultiUdpDiscover() {
return new MultiReceiver();
}
/**
*
*
* @return Receiver
*/
public static Receiver getUdpDiscover() {
return new UniReceiver();
}
}
}
[color=green][size=medium] 수용자 [/size][/color]
인터페이스
package com.gbcom.ccsv3.transport.multidiscover;
import java.net.UnknownHostException;
/**
* UDP
*
*
*
* @author syz
*
* @date 2015-6-26, 04:39:06
*
* @version v1.0.0
*
* @see com.gbcom.ccsv3.transport.multidiscover.Receiver
*/
public interface Receiver {
/**
*
*
* @throws UnknownHostException
* Exception
*/
public void start() throws UnknownHostException;
/**
*
*/
public void stop();
/**
*
*
* @return Boolean
*/
public boolean isStarted();
}
그룹 방송의 실현
package com.gbcom.ccsv3.transport.multidiscover;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.util.Date;
import org.apache.log4j.Logger;
/**
*
*
* * 1107 1108
*
*
*
* @author syz
*
* @date 2015-6-26, 04:25:33
*
* @version v1.0.0
*
* @see com.gbcom.ccsv3.transport.multidiscover.MultiReceiver
*/
public class MultiReceiver implements Receiver {
private static final Logger LOGGER = Logger.getLogger(MultiReceiver.class);
/**
* ip
*/
public static final String MULTI_GROUP_IP = "224.7.11.3";
/**
*
*/
public static final int MULTI_GROUP_PORT = 1107;
private MulticastSocket msr = null;
private InetAddress group = null;
private boolean started = false;
/**
*
*
* @throws UnknownHostException
* Exception
*/
@Override
public void start() throws UnknownHostException {
// socket
//
this.group = InetAddress.getByName(MULTI_GROUP_IP);//
try {
msr = new MulticastSocket(MULTI_GROUP_PORT); // server bind port
//java.net.SocketException: No such device
// at java.net.PlainDatagramSocketImpl.join(Native Method)
// at java.net.PlainDatagramSocketImpl.join(PlainDatagramSocketImpl.java:181)
// at java.net.MulticastSocket.joinGroup(MulticastSocket.java:277)
// at com.gbcom.ccsv3.transport.multidiscover.MultiReceiver.start(MultiReceiver.java:56)
// at com.gbcom.ccsv3.transport.multidiscover.DiscoverServer$1.run(DiscoverServer.java:50)
// at java.lang.Thread.run(Thread.java:662)
msr.joinGroup(group);//
byte[] buffer = new byte[50];
LOGGER.info("Thread=" + Thread.currentThread()
+ " ; MultiReceiver started!!! ( : " + new Date() + ")");
started = true;
while (true) {
try {
//
DatagramPacket dp = new DatagramPacket(buffer,
buffer.length);
msr.receive(dp);
DpDispatcher.getInstance().addDp(dp);
} catch (Exception e) {
LOGGER.error("receiver is error , continue", e);
continue;
}
}
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("MultiDiscover --- start -- error", e);
} finally {
if (msr != null) {
try {
msr.leaveGroup(group);
msr.close();
} catch (Exception e) {
LOGGER.error("MultiDiscover --- start finall -- error", e);
}
}
}
}
/**
*
*/
@Override
public void stop() {
if (msr != null) {
try {
msr.leaveGroup(group);
msr.close();
} catch (Exception e) {
LOGGER.error("MultiDiscover --- start finall -- error", e);
}
}
started = false;
}
/**
*
*
* @return started
*/
@Override
public boolean isStarted() {
return started;
}
}
[size=medium][color=green] 발송자 [/color][/size]
package com.gbcom.ccsv3.transport.multidiscover;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* UDP
*
*
*
* @author syz
*
* @date 2015-6-26, 04:39:06
*
* @version v1.0.0
*
* @see Sender
*/
public interface Sender {
/**
* 。 ip port , ,
*
* @param msg
* String
* @param ip
* InetAddress
* @param port
* int
* @throws UnknownHostException
* Exception
*/
public void send(String msg, InetAddress ip, int port)
throws UnknownHostException;
}
그룹 방송 실현
package com.gbcom.ccsv3.transport.multidiscover;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import org.apache.log4j.Logger;
/**
* , * 1107 1108
*
*
*
* @author syz
*
* @date 2015-6-26, 04:25:33
*
* @version v1.0.0
*
* @see MultiSender
*/
public final class MultiSender implements Sender {
private static final Logger LOGGER = Logger.getLogger(MultiSender.class);
/**
* ip
*/
public static final String MULTI_GROUP_IP = "224.7.11.3";
/**
*
*/
public static final int MULTI_GROUP_PORT = 1108;
private static final MultiSender INSTANCE = new MultiSender();
/**
* ,
*
* @return MultiSender
*/
public static MultiSender getInstance() {
return INSTANCE;
}
private MultiSender() {
}
/**
* @param msg
* String
* @param ip
* InetAddress
* @param port
* int
* @throws UnknownHostException
* Exception
*/
@Override
public void send(String msg, InetAddress ip, int port)
throws UnknownHostException {
InetAddress group = InetAddress.getByName(MULTI_GROUP_IP);//
MulticastSocket mss = null;
try {
// mss = new MulticastSocket(MULTI_GROUP_PORT);
mss = new MulticastSocket(); // client
mss.joinGroup(group);
byte[] buffer = msg.getBytes();
DatagramPacket dp = new DatagramPacket(buffer, buffer.length,
group, MULTI_GROUP_PORT);
mss.send(dp);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("MultiSender -- send", e);
} finally {
try {
if (mss != null) {
mss.leaveGroup(group);
mss.close();
}
} catch (Exception e) {
LOGGER.error("MultiSender -- send -- final", e);
}
}
}
}
[size=medium][color=green]
프로세서 구현 [/color][/size]
package com.gbcom.ccsv3.transport.multidiscover;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.log4j.Logger;
import com.gbcom.omc.si.common.Const;
/**
* , dp
*
*
*
* @author syz
*
* @date 2015-6-26, 04:29:42
*
* @version v1.0.0
*
* @see com.gbcom.ccsv3.transport.multidiscover.DpDispatcher
*/
public class DpDispatcher {
private static final Logger LOG = Logger.getLogger(DpDispatcher.class);
private static final int THREAD_NUM = 1;
private static final int BLOCK_QUEUE_MAX_SIZE = 10000;
private static final int BLOCK_QUEUE_CLEAR_SIZE = 10000;
/**
*
*/
private ExecutorService executor = null;
private boolean isRunning = false;
/**
* Trap :SIZE
*/
private BlockingQueue dpQueue = new LinkedBlockingQueue(
BLOCK_QUEUE_MAX_SIZE);
private static class DpDispatcherHolder {
private static final DpDispatcher INSTANCE = new DpDispatcher();
}
/**
*
*
* @return TaskDispatcher
*/
public static DpDispatcher getInstance() {
return DpDispatcherHolder.INSTANCE;
}
private DpDispatcher() {
init();
start();
}
private void init() {
isRunning = false;
}
/**
*
*
* @param dp
* DatagramPacket
*/
public void addDp(DatagramPacket dp) {
if (!isRunning) {
LOG
.error("UdpDispatcher is not running, the Task below may not process");
}
if (LOG.isDebugEnabled()) {
LOG.debug("add DatagramPacket to Queue,, Address="
+ dp.getAddress());
}
try {
if (dpQueue.size() >= BLOCK_QUEUE_CLEAR_SIZE) {
LOG
.info(" *****cleart request Task***** trap queue size is more than "
+ BLOCK_QUEUE_CLEAR_SIZE
+ ";; CLEAR BlockingQueue");
dpQueue.clear();
}
dpQueue.put(dp);
} catch (InterruptedException e) {
LOG.info("/******* add dp InterruptedException*********/");
LOG.error("add dp to queue interrupted", e);
LOG.info("/******* add dp InterruptedException *********/");
} catch (Exception e) {
LOG.error("Other Exception ", e);
}
}
/**
*
*/
public void stop() {
executor.shutdownNow();
isRunning = false;
}
/**
*
*/
public void start() {
executor = Executors.newCachedThreadPool();
for (int i = 0; i < THREAD_NUM; i++) {
executor.execute(new DispatcherTask());
}
isRunning = true;
LOG.info("do Dispatcher task start , current thread size = "
+ THREAD_NUM);
}
class DispatcherTask implements Runnable {
/**
*
*/
@Override
public void run() {
DatagramPacket dp = null;
while (!Thread.currentThread().isInterrupted()) {
try {
long begin = System.currentTimeMillis();
dp = dpQueue.take();
String s = new String(dp.getData(), 0, dp.getLength());
LOG.info("discover receiver dp , msg=" + s
+ ",dpQueue size=" + dpQueue.size());
if (s.equalsIgnoreCase("who")) {
/*
* TransportMapping mapping
* =SnmpSingleton.getTransportMapping(); if(mapping
* instanceof DefaultUdpTransportMapping){ String ip =
* ((DefaultUdpTransportMapping)mapping).getAddress().
* getInetAddress().toString();
* SenderFactory.getMultiSender().send(ip); }
*/
String ip = "NULL";
int port = 162;
if (Const.sourceSnmpIp == null
|| Const.sourceSnmpIp.trim().equals("")) {
ip = InetAddress.getLocalHost().getHostAddress()
.toString();
} else {
String[] udpSrc = (Const.sourceSnmpIp.trim())
.split("/");
if (udpSrc.length < 1 || udpSrc.length > 2) {
ip = InetAddress.getLocalHost()
.getHostAddress().toString();
} else {
ip = udpSrc[0];
port = (udpSrc.length == 2) ? Integer
.parseInt(udpSrc[1]) : 162;
}
}
String msg = "IP:" + ip + "," + "PORT:" + port;
// InetAddress addr =
// InetAddress.getByName(MultiSender.MULTI_GROUP_IP);
// SenderFactory.getMultiSender().send(msg,MultiSender.MULTI_GROUP_IP,MultiSender.MULTI_GROUP_PORT);
SenderFactory.getUniSender().send(msg, dp.getAddress(),
dp.getPort());
} else {
// LOG.error("OTHER INFOR---"+s);
}
if (LOG.isDebugEnabled()) {
LOG.info("process Task success, thread="
+ Thread.currentThread().getName()
+ " ;spend time :total= "
+ ((System.currentTimeMillis() - begin) / 1000)
+ "s || the queue size is not actually:"
+ dpQueue.size());
}
} catch (InterruptedException e) {
LOG
.info("/******* DP Dispatcher InterruptedException*********/");
LOG.error("DP Dispatcher thread interrupted ;; tread = "
+ Thread.currentThread().getName(), e);
LOG
.info("/******* DP Dispatcher InterruptedException*********/");
Thread.currentThread().interrupt();
break;
} catch (Exception e) {
LOG.error("DP Dispatcher thread exception", e);
continue;
}
}
}
}
public static class SenderFactory {
/**
*
*
* @return Sender
*/
public static Sender getMultiSender() {
return MultiSender.getInstance();
}
/**
*
*
* @return UniSender
*/
public static Sender getUniSender() {
return UniSender.getInstance();
}
}
}
검색 서버를 열고 프로세서 모듈을 확장하면 됩니다.
예시 코드는udp만 지원합니다. 전체 코드 참조 첨부 파일입니다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.