当前位置: 首页>>代码示例>>Java>>正文


Java MulticastSocket.setTimeToLive方法代码示例

本文整理汇总了Java中java.net.MulticastSocket.setTimeToLive方法的典型用法代码示例。如果您正苦于以下问题:Java MulticastSocket.setTimeToLive方法的具体用法?Java MulticastSocket.setTimeToLive怎么用?Java MulticastSocket.setTimeToLive使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.net.MulticastSocket的用法示例。


在下文中一共展示了MulticastSocket.setTimeToLive方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: createSocket

import java.net.MulticastSocket; //导入方法依赖的package包/类
/**
 * Creates multicast socket and joins multicast group.
 *
 * @throws IOException If fails to create socket or join multicast group.
 * @return Multicast socket.
 */
private MulticastSocket createSocket() throws IOException {
    MulticastSocket sock = new MulticastSocket(mcastPort);

    sock.setLoopbackMode(false); // Use 'false' to enable support for more than one node on the same machine.

    if (sockItf != null)
        sock.setInterface(sockItf);

    if (sock.getLoopbackMode())
        U.warn(log, "Loopback mode is disabled which prevents nodes on the same machine from discovering " +
            "each other.");

    sock.joinGroup(mcastGrp);

    if (ttl != -1)
        sock.setTimeToLive(ttl);

    return sock;
}
 
开发者ID:apache,项目名称:ignite,代码行数:26,代码来源:TcpDiscoveryMulticastIpFinder.java

示例2: init

import java.net.MulticastSocket; //导入方法依赖的package包/类
synchronized public void init(InetAddress bindAddress, Router router, DatagramProcessor datagramProcessor) throws InitializationException {

        this.router = router;
        this.datagramProcessor = datagramProcessor;

        try {

            // TODO: UPNP VIOLATION: The spec does not prohibit using the 1900 port here again, however, the
            // Netgear ReadyNAS miniDLNA implementation will no longer answer if it has to send search response
            // back via UDP unicast to port 1900... so we use an ephemeral port
            log.info("Creating bound socket (for datagram input/output) on: " + bindAddress);
            localAddress = new InetSocketAddress(bindAddress, 0);
            socket = new MulticastSocket(localAddress);
            socket.setTimeToLive(configuration.getTimeToLive());
            socket.setReceiveBufferSize(262144); // Keep a backlog of incoming datagrams if we are not fast enough
        } catch (Exception ex) {
            throw new InitializationException("Could not initialize " + getClass().getSimpleName() + ": " + ex);
        }
    }
 
开发者ID:offbye,项目名称:DroidDLNA,代码行数:20,代码来源:DatagramIOImpl.java

示例3: init

import java.net.MulticastSocket; //导入方法依赖的package包/类
private void init()
    throws IOException
{
    ms = new MulticastSocket(advertisePort);
    ms.setTimeToLive(16);
    ms.joinGroup(InetAddress.getByName(groupAddress));
    initialized = true;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:9,代码来源:AdvertiseListener.java

示例4: test

import java.net.MulticastSocket; //导入方法依赖的package包/类
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);
		}
	}
}
 
开发者ID:leolewis,项目名称:openvisualtraceroute,代码行数:28,代码来源:UDP.java

示例5: openSocket

import java.net.MulticastSocket; //导入方法依赖的package包/类
private void openSocket() throws IOException
{
    closeSocket();
    socket = new MulticastSocket(DISCOVERY_PORT);
    socket.setTimeToLive(10);
    socket.setSoTimeout(1);
    socket.setInterface(Network.getPrimaryAddress());
    socket.joinGroup(InetAddress.getByName(DISCOVERY_GROUP));
    log.info(String.format("Joined %s on %s", DISCOVERY_GROUP, socket.getInterface()));
}
 
开发者ID:drytoastman,项目名称:scorekeeperfrontend,代码行数:11,代码来源:Discovery.java

示例6: muc

import java.net.MulticastSocket; //导入方法依赖的package包/类
public void muc() throws IOException{
 MulticastSocket msocket = new MulticastSocket(port);
 msocket.joinGroup(InetAddress.getByName("239.12.6.254"));
 msocket.setTimeToLive(4);
 String content = "";
 DatagramPacket packet = new DatagramPacket(
   content.getBytes(), content.getBytes().length, InetAddress.getByName("10.12.6.24"), port);
 msocket.send(packet);
}
 
开发者ID:zongyl,项目名称:smartLink,代码行数:10,代码来源:SnifferSmartLinker.java

示例7: createSockets

import java.net.MulticastSocket; //导入方法依赖的package包/类
/**
 * Creates an array of sockets with TTL and network interface set.
 *
 * @param mcastTTL multicast TTL.
 * @return an array of multicast sockets to broadcast on.
 * @throws IOException if I/O error occurred while creating a multicast socket.
 * @noinspection SocketOpenedButNotSafelyClosed, ConstantConditions
 */
private static MulticastSocket[] createSockets(final int mcastTTL) throws IOException {

   Exception lastException = null; // Records last error in case we could not create any sockets
   final List<MulticastSocket> socketList = new ArrayList<MulticastSocket>(11);
   final Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
   while (enumeration.hasMoreElements()) {
      try {
         final NetworkInterface netIf = enumeration.nextElement();
         if (netIf.supportsMulticast()) {

            final MulticastSocket socket = new MulticastSocket(); // NOPMD
            socket.setTimeToLive(mcastTTL);
            socket.setNetworkInterface(netIf);
            socket.setSendBufferSize(SEND_BUFFER_SIZE);
            socketList.add(socket);
         }
      } catch (final Exception e) {

         lastException = e;
         ExceptionUtils.ignoreException(e, "continue to connect to those we can");
      }
   }
   if (socketList.isEmpty()) {
      throw new IOException("Could not create at least one multicast socket. Last error: " + lastException);
   }
   return socketList.toArray(new MulticastSocket[socketList.size()]);
}
 
开发者ID:cacheonix,项目名称:cacheonix-core,代码行数:36,代码来源:PlainMulticastSender.java

示例8: discover

import java.net.MulticastSocket; //导入方法依赖的package包/类
/**
 * Sends a discovery packet for the specified service and listens for reply packets, notifying
 * a callback as services are discovered.
 * @param serviceType the type of service to query in mDNS, e.g. {@code "_example._tcp.local"}
 * @param callback receives callbacks with {@link Result} objects as answers are decoded from
 *                 incoming reply packets.
 * @param timeout duration in milliseconds to wait for answer packets. If {@code 0}, this method
 *                will listen forever.
 * @throws IOException
 */
public static void discover(String serviceType, Callback callback, int timeout) throws IOException {
    if (timeout < 0) throw new IllegalArgumentException();
    InetAddress group = InetAddress.getByName(MULTICAST_GROUP_ADDRESS);
    MulticastSocket sock = new MulticastSocket();   // binds to a random free source port
    if (DEBUG) System.out.println("Source port is " + sock.getLocalPort());
    byte[] data = discoverPacket(serviceType);
    if (DEBUG) System.out.println("Query packet:");
    if (DEBUG) hexdump(data, 0, data.length);
    DatagramPacket packet = new DatagramPacket(data, data.length, group, PORT);
    sock.setTimeToLive(255);
    sock.send(packet);
    byte[] buf = new byte[1024];
    packet = new DatagramPacket(buf, buf.length);
    long endTime = 0;
    if (timeout != 0) {
        endTime = System.currentTimeMillis() + timeout;
    }
    while (true) {
        if (timeout != 0) {
            int remaining = (int) (endTime - System.currentTimeMillis());
            if (remaining <= 0) {
                break;
            }
            sock.setSoTimeout(remaining);
        }
        try {
            sock.receive(packet);
        } catch (SocketTimeoutException e) {
            break;
        }
        if (DEBUG) System.out.println("\n\nIncoming packet:");
        if (DEBUG) hexdump(packet.getData(), 0, packet.getLength());
        Result result = decode(packet.getData(), packet.getLength());
        if (callback != null) {
            callback.onResult(result);
        }
    }
}
 
开发者ID:youviewtv,项目名称:tinydnssd,代码行数:49,代码来源:MDNSDiscover.java

示例9: resolve

import java.net.MulticastSocket; //导入方法依赖的package包/类
/**
 * Ask for the A, SRV and TXT records of a particular service.
 * @param serviceName the name of service to query in mDNS, e.g.
 *                    {@code "device-1234._example._tcp.local"}
 * @param timeout duration in milliseconds to wait for an answer packet. If {@code 0}, this
 *                method will listen forever.
 * @return the reply packet's decoded answer data
 * @throws IOException
 */
public static Result resolve(String serviceName, int timeout) throws IOException {
    if (timeout < 0) throw new IllegalArgumentException();
    InetAddress group = InetAddress.getByName(MULTICAST_GROUP_ADDRESS);
    MulticastSocket sock = new MulticastSocket();   // binds to a random free source port
    if (DEBUG) System.out.println("Source port is " + sock.getLocalPort());
    if (DEBUG) System.out.println("Query packet:");
    byte[] data = queryPacket(serviceName, QCLASS_INTERNET | CLASS_FLAG_UNICAST, QTYPE_A, QTYPE_SRV, QTYPE_TXT);
    if (DEBUG) hexdump(data, 0, data.length);
    DatagramPacket packet = new DatagramPacket(data, data.length, group, PORT);
    sock.setTimeToLive(255);
    sock.send(packet);
    byte[] buf = new byte[1024];
    packet = new DatagramPacket(buf, buf.length);
    Result result = new Result();
    long endTime = 0;
    if (timeout != 0) {
        endTime = System.currentTimeMillis() + timeout;
    }
    // records could be returned in different packets, so we have to loop
    // timeout applies to the acquisition of ALL packets
    while (result.a == null || result.srv == null || result.txt == null) {
        if (timeout != 0) {
            int remaining = (int) (endTime - System.currentTimeMillis());
            if (remaining <= 0) {
                break;
            }
            sock.setSoTimeout(remaining);
        }
        sock.receive(packet);
        if (DEBUG) System.out.println("\n\nIncoming packet:");
        if (DEBUG) hexdump(packet.getData(), 0, packet.getLength());
        decode(packet.getData(), packet.getLength(), result);
    }
    return result;
}
 
开发者ID:youviewtv,项目名称:tinydnssd,代码行数:45,代码来源:MDNSDiscover.java

示例10: setUpSocket

import java.net.MulticastSocket; //导入方法依赖的package包/类
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;
}
 
开发者ID:andrey-desman,项目名称:openhab-hdl,代码行数:9,代码来源:SsdpDiscovery.java

示例11: sendData

import java.net.MulticastSocket; //导入方法依赖的package包/类
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);
}
 
开发者ID:phishman3579,项目名称:Bitcoin,代码行数:10,代码来源:Multicast.java

示例12: createSocket

import java.net.MulticastSocket; //导入方法依赖的package包/类
protected DatagramSocket createSocket() throws IOException {
    MulticastSocket s = new MulticastSocket();
    s.setSendBufferSize(maxTraceDatagramSize);
    s.setBroadcast(broadcast);
    s.setLoopbackMode(true);
    s.setTimeToLive(timeToLive);
    return s;
}
 
开发者ID:DiamondLightSource,项目名称:daq-eclipse,代码行数:9,代码来源:MulticastTraceBrokerPlugin.java

示例13: createCommandChannel

import java.net.MulticastSocket; //导入方法依赖的package包/类
protected CommandChannel createCommandChannel() throws IOException {
    socket = new MulticastSocket(mcastPort);
    socket.setLoopbackMode(loopBackMode);
    socket.setTimeToLive(timeToLive);

    LOG.debug("Joining multicast address: " + getMulticastAddress());
    socket.joinGroup(getMulticastAddress());
    socket.setSoTimeout((int)keepAliveInterval);

    return new CommandDatagramSocket(this, getWireFormat(), getDatagramSize(), getTargetAddress(), createDatagramHeaderMarshaller(), getSocket());
}
 
开发者ID:DiamondLightSource,项目名称:daq-eclipse,代码行数:12,代码来源:MulticastTransport.java

示例14: start

import java.net.MulticastSocket; //导入方法依赖的package包/类
/**
 * Starts a ServerSocket and a thread with this MulticastUDPSocket 
 * as the Runnable.
 */
public void start() {
	if (runner == null) {
		try {
			LOGGER.info("Multicast service : port " + portNumber + " group "+ groupAddress );
			group = InetAddress.getByName(groupAddress);
			serverSocket = new MulticastSocket(portNumber);
			//at least under Windows with multiple network interfaces, the multicast socket
			//sometimes gets confused and doesn't receive packets. Explicitly binding
			//to the network interface of InetAddress.getLocalHost seems to resolve the problem
			serverSocket.setInterface(InetAddress.getLocalHost());

			// Joins the group
			serverSocket.joinGroup(group);
			//serverSocket.setTTL(ttl); // Deprecated
			serverSocket.setTimeToLive(ttl);

			runner = new Thread(this);
			runner.start();

		} catch (IOException ioe) {
			System.out.println("MulticastUDPSocket init error: "+ioe
					+ " on port number "+portNumber
					+ " with group address " + groupAddress);
		}
	}
}
 
开发者ID:claudiotrindade,项目名称:contexttoolkit,代码行数:31,代码来源:MulticastUDPSocket.java

示例15: start

import java.net.MulticastSocket; //导入方法依赖的package包/类
/**
 * start the discovery agent
 * 
 * @throws Exception
 */
public void start() throws Exception {
	
    if (started.compareAndSet(false, true)) {        	
    	         	
        if (group == null || group.length() == 0) {
            throw new IOException("You must specify a group to discover");
        }
        String type = getType();
        if (!type.endsWith(".")) {
            LOG.warn("The type '" + type + "' should end with '.' to be a valid Discovery type");
            type += ".";
        }
        
        if (discoveryURI == null) {
            discoveryURI = new URI(DEFAULT_DISCOVERY_URI_STRING);
        }
        
        if (LOG.isTraceEnabled()) 
    	  	LOG.trace("start - discoveryURI = " + discoveryURI);        	  	        	  
    	  
    	  String myHost = discoveryURI.getHost();
    	  int    myPort = discoveryURI.getPort(); 
    	     
    	  if( DEFAULT_HOST_STR.equals(myHost) ) 
    	  	myHost = DEFAULT_HOST_IP;       	      	  
    	  
    	  if(myPort < 0 )
    	    myPort = DEFAULT_PORT;        	    
    	  
    	  if (LOG.isTraceEnabled()) {
    	  	LOG.trace("start - myHost = " + myHost); 
    	  	LOG.trace("start - myPort = " + myPort);   	
    	  	LOG.trace("start - group  = " + group );		       	  	
    	  	LOG.trace("start - interface  = " + mcInterface );
    	  	LOG.trace("start - network interface  = " + mcNetworkInterface );
    	  	LOG.trace("start - join network interface  = " + mcJoinNetworkInterface );
    	  }	
    	  
        this.inetAddress = InetAddress.getByName(myHost);
        this.sockAddress = new InetSocketAddress(this.inetAddress, myPort);
        mcast = new MulticastSocket(myPort);
        mcast.setLoopbackMode(loopBackMode);
        mcast.setTimeToLive(getTimeToLive());
        if (mcJoinNetworkInterface != null) {
            mcast.joinGroup(sockAddress, NetworkInterface.getByName(mcJoinNetworkInterface));
        }
        else {
        	mcast.joinGroup(inetAddress);
        }
        mcast.setSoTimeout((int)keepAliveInterval);
        if (mcInterface != null) {
            mcast.setInterface(InetAddress.getByName(mcInterface));
        }
        if (mcNetworkInterface != null) {
            mcast.setNetworkInterface(NetworkInterface.getByName(mcNetworkInterface));
        }
        runner = new Thread(this);
        runner.setName(this.toString() + ":" + runner.getName());
        runner.setDaemon(true);
        runner.start();
        doAdvertizeSelf();
    }
}
 
开发者ID:DiamondLightSource,项目名称:daq-eclipse,代码行数:69,代码来源:MulticastDiscoveryAgent.java


注:本文中的java.net.MulticastSocket.setTimeToLive方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。