下面列出了java.net.MulticastSocket#send ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Send an outgoing multicast DNS message.
*
* @param out
* @exception IOException
*/
public void send(DNSOutgoing out) throws IOException {
if (!out.isEmpty()) {
byte[] message = out.data();
final DatagramPacket packet = new DatagramPacket(message, message.length, _group, DNSConstants.MDNS_PORT);
if (logger.isLoggable(Level.FINEST)) {
try {
final DNSIncoming msg = new DNSIncoming(packet);
if (logger.isLoggable(Level.FINEST)) {
logger.finest("send(" + this.getName() + ") JmDNS out:" + msg.print(true));
}
} catch (final IOException e) {
logger.throwing(getClass().toString(), "send(" + this.getName() + ") - JmDNS can not parse what it sends!!!", e);
}
}
final MulticastSocket ms = _socket;
if (ms != null && !ms.isClosed()) {
ms.send(packet);
}
}
}
public void sendFrame(final Frame frame) throws IOException {
final byte[] message = toValidMessage(frame);
final DatagramPacket packet = new DatagramPacket(message, 0, message.length, mcastAddress, mcastPort);
for (final MulticastSocket mcastSocket : mcastSockets) {
try {
sentMessages++;
mcastSocket.send(packet);
} catch (final IOException e) {
final String exceptionMessage = e.getMessage();
if (exceptionMessage.endsWith(NO_BUFFER_SPACE_AVAILABLE)
|| exceptionMessage.endsWith(NO_ROUTE_TO_HOST)) {
final NetworkInterface networkInterface = mcastSocket.getNetworkInterface();
final InetAddress mcastSocketInterface = mcastSocket.getInterface();
LOG.warn(createIgnoredWarning(exceptionMessage, networkInterface, mcastSocketInterface));
} else {
throw e;
}
}
}
}
public static void main(String[] args) throws Exception {
if (args.length != 3) {
System.out.println("Usage: SAdvertize localaddress multicastaddress port");
System.out.println("java SAdvertize 10.16.88.178 224.0.1.105 23364");
System.out.println("send from 10.16.88.178:23364 to 224.0.1.105:23364");
System.exit(1);
}
InetAddress group = InetAddress.getByName(args[1]);
InetAddress addr = InetAddress.getByName(args[0]);
int port = Integer.parseInt(args[2]);
InetSocketAddress addrs = new InetSocketAddress(addr, port);
MulticastSocket s = new MulticastSocket(addrs);
s.setTimeToLive(29);
s.joinGroup(group);
boolean ok = true;
while (ok) {
byte[] buf = new byte[1000];
DatagramPacket recv = new DatagramPacket(buf, buf.length, group, port);
System.out.println("sending from: " + addr);
s.send(recv);
Thread.currentThread().sleep(2000);
}
s.leaveGroup(group);
}
private static void test() throws Exception {
final String hostname = "google.com";
final String localhost = "localhost";
final MulticastSocket datagramSocket = new MulticastSocket();
datagramSocket.setSoTimeout(10000);
short ttl = 1;
final InetAddress receiverAddress = InetAddress.getByName(hostname);
while (ttl < 100) {
try {
byte[] buffer = "0123456789".getBytes();
datagramSocket.setTimeToLive(ttl++);
final DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, receiverAddress, 80);
datagramSocket.send(sendPacket);
buffer = new byte[10];
final DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
datagramSocket.receive(receivePacket);
System.out.println("ttl=" + ttl + " address=" + receivePacket.getAddress().getHostAddress() + " data="
+ new String(receivePacket.getData()));
Thread.sleep(1000);
} catch (final SocketTimeoutException e) {
System.out.println("timeout ttl=" + ttl);
}
}
}
public static void main(String[] args) {
try {
InetAddress group = InetAddress.getByName(address);
MulticastSocket multicastSocket = new MulticastSocket(port);
multicastSocket.joinGroup(group);
while (true) {
byte[] buffer = "One".getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, port);
multicastSocket.send(packet);
Thread.sleep(1000);
}
} catch (Exception e) {
log.error("", e);
}
}
public static void sendData(MulticastSocket s, int ourTTL, byte[] buffer) throws IOException {
// Create a DatagramPacket
final DatagramPacket pack = new DatagramPacket(buffer, buffer.length, InetAddress.getByName(GROUP), PORT);
// Get the current TTL, set our TTL, do a send, reset the TTL
final int ttl = s.getTimeToLive();
s.setTimeToLive(ourTTL);
s.send(pack);
s.setTimeToLive(ttl);
}
/**
* Broadcasts a SSDP discovery message into the network to find provided
* services.
*
* @return The Socket the answers will arrive at.
* @throws UnknownHostException
* @throws IOException
* @throws SocketException
* @throws UnsupportedEncodingException
*/
private MulticastSocket sendDiscoveryBroacast()
throws UnknownHostException, IOException, SocketException, UnsupportedEncodingException {
InetAddress multicastAddress = InetAddress.getByName("239.255.255.250");
final int port = 1900;
MulticastSocket socket = new MulticastSocket(port);
socket.setReuseAddress(true);
socket.setSoTimeout(130000);
socket.joinGroup(multicastAddress);
byte[] requestMessage = DISCOVER_MESSAGE.getBytes("UTF-8");
DatagramPacket datagramPacket = new DatagramPacket(requestMessage, requestMessage.length, multicastAddress,
port);
socket.send(datagramPacket);
return socket;
}
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();
}
}
public void startDiscover() {
try {
mMulticastSocket = new MulticastSocket(Constant.HID_MULTICAST_PORT);
group = InetAddress.getByName(Constant.HID_MULTICAST_ADDRESS);
mMulticastSocket.joinGroup(group);
} catch (IOException e) {
e.printStackTrace();
return;
}
listenerThread = new Thread(new Runnable() {
// listen response from pc.
@Override
public void run() {
try {
DatagramPacket packet;
packet = new DatagramPacket(new byte[256], 256);
while (true) {
mMulticastSocket.receive(packet);
String rsp = new String(packet.getData()).trim();
Log.d(TAG, "rsp: " + rsp);
if (Constant.HID_SERVICE_DISCOVERY_RSP.equals(rsp)) {
Log.d(TAG, "get response from pc.");
break;
} else {
Log.d(TAG, "It is not a valid response, just ignore it.");
packet.setData(new byte[256]);
}
}
// send message to activity to stop progress dialog.
if (mUIHandler != null) {
mUIHandler.obtainMessage(MainActivity.MSG_FOUND_SERVICE).sendToTarget();
}
mPCIPAddress = packet.getAddress();
Log.d(TAG, "pc ip address: " + packet.getSocketAddress().toString());
// interrupt scanner thread to stop scan cause we have found pc.
scannerThread.interrupt();
// start data send thread.
new DataSendThread().start();
} catch (IOException e) {
e.printStackTrace();
}
}
});
scannerThread = new Thread(new Runnable() {
// pc finder thread.
@Override
public void run() {
try {
DatagramPacket packet = new DatagramPacket(Constant.HID_SERVICE_DISCOVERY_REQ.getBytes(),
Constant.HID_SERVICE_DISCOVERY_REQ.length(),
group, Constant.HID_MULTICAST_PORT);
while (true) {
if (scannerThread.isInterrupted()) {
break;
}
Log.d(TAG, "discovery pc......");
mMulticastSocket.send(packet);
// try again after 2s.
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
// start discover thread.
scannerThread.start();
listenerThread.start();
}
private void askWithGroup(InetAddress group, MulticastSocket socket) throws IOException {
DatagramPacket packet = new DatagramPacket(buffer.array(), buffer.position(), group, Query.MDNS_PORT);
packet.setAddress(group);
socket.send(packet);
}