use of java.net.MulticastSocket in project quickstarts by jboss-switchyard.
the class CamelNettyBindingTest method sendTextMessageThroughUdp.
@Test
public void sendTextMessageThroughUdp() throws Exception {
// replace existing implementation for testing purposes
_testKit.removeService("DefaultGreetingService");
final MockHandler greetingService = _testKit.registerInOnlyService("DefaultGreetingService");
MulticastSocket clientSocket = new MulticastSocket();
InetAddress group = InetAddress.getByName("localhost");
byte[] datagramBody = PAYLOAD.getBytes(Charset.defaultCharset());
DatagramPacket packet = new DatagramPacket(datagramBody, 0, datagramBody.length, group, 3940);
clientSocket.send(packet);
// sleep a bit to receive message on camel side
clientSocket.close();
greetingService.waitForOKMessage();
final LinkedBlockingQueue<Exchange> recievedMessages = greetingService.getMessages();
assertThat(recievedMessages, is(notNullValue()));
final Exchange recievedExchange = recievedMessages.iterator().next();
String content = recievedExchange.getMessage().getContent(String.class);
// the receive content is trimmed because extra bytes appended to frame by receiver
assertThat(PAYLOAD, is(equalTo(content.trim())));
}
use of java.net.MulticastSocket in project openhab1-addons by openhab.
the class SsdpDiscovery method setUpSocket.
private static MulticastSocket setUpSocket() throws IOException {
MulticastSocket recSocket = new MulticastSocket(null);
recSocket.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), PORT));
recSocket.setTimeToLive(10);
recSocket.setSoTimeout(1000);
recSocket.setBroadcast(true);
return recSocket;
}
use of java.net.MulticastSocket in project openhab1-addons by openhab.
the class SsdpDiscovery method sendNotify.
private static void sendNotify(String notifyMessage, InetAddress ia) throws Exception {
MulticastSocket socket = new MulticastSocket(null);
try {
socket.bind(new InetSocketAddress(PORT));
socket.setTimeToLive(4);
byte[] data = notifyMessage.toString().getBytes();
socket.send(new DatagramPacket(data, data.length, new InetSocketAddress(ia, PORT)));
} catch (Exception e) {
logger.error("sendNotify", e);
throw e;
} finally {
socket.disconnect();
socket.close();
}
}
use of java.net.MulticastSocket in project openhab1-addons by openhab.
the class SsdpDiscovery method retrieveResponse.
static Map<String, Map<String, String>> retrieveResponse() throws Exception {
String response = null;
Map<String, Map<String, String>> result = new HashMap<String, Map<String, String>>();
MulticastSocket recSocket = setUpSocket();
int i = 0;
logger.debug("Retrieving response");
while (i < 10) {
byte[] buf = new byte[2048];
DatagramPacket input = new DatagramPacket(buf, buf.length);
try {
recSocket.receive(input);
response = new String(input.getData());
Map<String, String> parsedResponse = parseResponse(response);
result.put(parsedResponse.get("IP"), parsedResponse);
} catch (SocketTimeoutException e) {
if (i >= 10) {
break;
}
i++;
}
}
logger.debug("Response retrieved: {}", result);
return result;
}
use of java.net.MulticastSocket in project openhab1-addons by openhab.
the class WemoBinding method wemoDiscovery.
public void wemoDiscovery() {
logger.debug("wemoDiscovery() is called!");
try {
final int SSDP_PORT = 1900;
final int SSDP_SEARCH_PORT = 1901;
// Broadcast address
final String SSDP_IP = "239.255.255.250";
// Connection timeout
int TIMEOUT = 1000;
// Send from localhost:1901
InetAddress localhost = InetAddress.getLocalHost();
InetSocketAddress srcAddress = new InetSocketAddress(localhost, SSDP_SEARCH_PORT);
// Send to 239.255.255.250:1900
InetSocketAddress dstAddress = new InetSocketAddress(InetAddress.getByName(SSDP_IP), SSDP_PORT);
// Request-Packet-Constructor
StringBuffer discoveryMessage = new StringBuffer();
discoveryMessage.append("M-SEARCH * HTTP/1.1\r\n");
discoveryMessage.append("HOST: " + SSDP_IP + ":" + SSDP_PORT + "\r\n");
discoveryMessage.append("MAN: \"ssdp:discover\"\r\n");
discoveryMessage.append("MX: 5\r\n");
discoveryMessage.append("ST: urn:Belkin:service:basicevent:1\r\n");
discoveryMessage.append("\r\n");
logger.trace("Request: {}", discoveryMessage.toString());
byte[] discoveryMessageBytes = discoveryMessage.toString().getBytes();
DatagramPacket discoveryPacket = new DatagramPacket(discoveryMessageBytes, discoveryMessageBytes.length, dstAddress);
// Send multi-cast packet
MulticastSocket multicast = null;
try {
multicast = new MulticastSocket(null);
multicast.bind(srcAddress);
logger.trace("Source-Address = '{}'", srcAddress);
multicast.setTimeToLive(5);
logger.trace("Send multicast request.");
multicast.send(discoveryPacket);
} finally {
logger.trace("Multicast ends. Close connection.");
multicast.disconnect();
multicast.close();
}
// Response-Listener
MulticastSocket wemoReceiveSocket = null;
DatagramPacket receivePacket = null;
try {
wemoReceiveSocket = new MulticastSocket(SSDP_SEARCH_PORT);
wemoReceiveSocket.setTimeToLive(10);
wemoReceiveSocket.setSoTimeout(TIMEOUT);
logger.debug("Send datagram packet.");
wemoReceiveSocket.send(discoveryPacket);
while (true) {
try {
logger.debug("Receive SSDP Message.");
receivePacket = new DatagramPacket(new byte[2048], 2048);
wemoReceiveSocket.receive(receivePacket);
final String message = new String(receivePacket.getData());
if (message.contains("Belkin")) {
logger.trace("Received message: {}", message);
}
new Thread(new Runnable() {
@Override
public void run() {
if (message != null) {
String location = StringUtils.substringBetween(message, "LOCATION: ", "/setup.xml");
String udn = StringUtils.substringBetween(message, "USN: uuid:", "::urn:Belkin");
if (udn != null) {
logger.trace("Save location '{}' for WeMo device with UDN '{}'", location, udn);
wemoConfigMap.put(udn, location);
logger.info("Wemo Device with UDN '{}' discovered", udn);
}
}
}
}).start();
} catch (SocketTimeoutException e) {
logger.debug("Message receive timed out.");
for (String name : wemoConfigMap.keySet()) {
logger.trace(name + ":" + wemoConfigMap.get(name));
}
break;
}
}
} finally {
if (wemoReceiveSocket != null) {
wemoReceiveSocket.disconnect();
wemoReceiveSocket.close();
}
}
} catch (Exception e) {
logger.error("Could not start wemo device discovery", e);
}
}
Aggregations