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


Java MulticastSocket.setSoTimeout方法代码示例

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


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

示例1: PacketReceiver

import java.net.MulticastSocket; //导入方法依赖的package包/类
public PacketReceiver( MessageListener listener ) 
{
   messageListener = listener; // set MessageListener
   
   try // connect MulticastSocket to multicast address and port 
   {
      // create new MulticastSocket
      multicastSocket = new MulticastSocket(
         MULTICAST_LISTENING_PORT );
      
      // use InetAddress to get multicast group
      multicastGroup = InetAddress.getByName( MULTICAST_ADDRESS );
      
      // join multicast group to receive messages
      multicastSocket.joinGroup( multicastGroup ); 
      
      // set 5 second timeout when waiting for new packets
      multicastSocket.setSoTimeout( 5000 );
   } // end try
   catch ( IOException ioException ) 
   {
      ioException.printStackTrace();
   } // end catch
}
 
开发者ID:cleitonferreira,项目名称:LivroJavaComoProgramar10Edicao,代码行数:25,代码来源:PacketReceiver.java

示例2: sendDiscoveryBroacast

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

示例3: scanResposesForKeywords

import java.net.MulticastSocket; //导入方法依赖的package包/类
/**
 * Scans all messages that arrive on the socket and scans them for the
 * search keywords. The search is not case sensitive.
 * 
 * @param socket
 *            The socket where the answers arrive.
 * @param keywords
 *            The keywords to be searched for.
 * @return
 * @throws IOException
 */
private String scanResposesForKeywords(MulticastSocket socket,
		String... keywords) throws IOException {
	// In the worst case a SocketTimeoutException raises
	socket.setSoTimeout(2000);
	do {
		logger.debug("Got an answer message.");
		byte[] rxbuf = new byte[8192];
		DatagramPacket packet = new DatagramPacket(rxbuf, rxbuf.length);
		socket.receive(packet);
		String foundIp = analyzePacket(packet, keywords);
		if (foundIp != null) {
			return foundIp;
		}
	} while (true);
}
 
开发者ID:andrey-desman,项目名称:openhab-hdl,代码行数:27,代码来源:SsdpDiscovery.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: initCast

import java.net.MulticastSocket; //导入方法依赖的package包/类
/**
 * 默认局域网内组播
 */
private void initCast(){
	try {
		cast = new MulticastSocket(port);
		cast.setSoTimeout(receiveTimeOut);
		cast.joinGroup(group);
	} catch (IOException e) {
		throw new TiandeMultiCastException(e.getMessage());
	}
}
 
开发者ID:lmd,项目名称:multicast,代码行数:13,代码来源:TiandeMulticastSocket.java

示例7: call

import java.net.MulticastSocket; //导入方法依赖的package包/类
@Override
public Object call() throws Exception {
    InetAddress multicastAddress = InetAddress.getByName(this.SSDP_HOST);
   
    MulticastSocket socket = new MulticastSocket(SSDP_PORT);
    socket.setReuseAddress(true);
    socket.setSoTimeout(10000);
    socket.joinGroup(multicastAddress);
    
    
    byte[] packetBuffer = SSDP_REQUEST().getBytes("UTF-8");
    DatagramPacket mSearchPacket = new DatagramPacket(packetBuffer, packetBuffer.length, multicastAddress, SSDP_PORT);
    socket.send(mSearchPacket);
    
    /**
     * Should run until either:
     * - A compatible device is found
     * - The socket times out (10000ms)
     */
    while(true){
        
        byte[] responseBuffer = new byte[8192];
            DatagramPacket packet = new DatagramPacket(responseBuffer, responseBuffer.length);
            socket.receive(packet);

            String packetAddress = packet.getAddress().getHostAddress();
            
            String fullResponse = new String(responseBuffer, 0, packet.getLength());
            
            /**
             * Make sure the response is not from localhost and the USN contains the HEOS urn.
             */
            if(!packetAddress.equals(InetAddress.getLocalHost().getHostAddress())){
              if(fullResponse.contains(SSDP_ST)){
                    return packetAddress;
                }
            }                
    }
}
 
开发者ID:bart-kneepkens,项目名称:OpenHeosControl,代码行数:40,代码来源:SsdpCallable.java

示例8: findHeosIp

import java.net.MulticastSocket; //导入方法依赖的package包/类
public String findHeosIp() throws UnknownHostException, IOException{
    
    InetAddress multicastAddress = InetAddress.getByName(this.SSDP_HOST);
   
    MulticastSocket socket = new MulticastSocket(SSDP_PORT);
    socket.setReuseAddress(true);
    socket.setSoTimeout(10000);
    socket.joinGroup(multicastAddress);
    
    
    byte[] packetBuffer = SSDP_REQUEST().getBytes("UTF-8");
    DatagramPacket mSearchPacket = new DatagramPacket(packetBuffer, packetBuffer.length, multicastAddress, SSDP_PORT);
    socket.send(mSearchPacket);
    
    /**
     * Should run until either:
     * - A compatible device is found
     * - The socket times out
     */
    while(true){
        
        byte[] responseBuffer = new byte[8192];
            DatagramPacket packet = new DatagramPacket(responseBuffer, responseBuffer.length);
            socket.receive(packet);

            String packetAddress = packet.getAddress().getHostAddress();
            
            String fullResponse = new String(responseBuffer, 0, packet.getLength());
            
            /**
             * Make sure the response is not from localhost and the USN contains the HEOS urn.
             */
            if(!packetAddress.equals(InetAddress.getLocalHost().getHostAddress())){
              if(fullResponse.contains(SSDP_ST)){
                    return packetAddress;
                }
            }                
    }
}
 
开发者ID:bart-kneepkens,项目名称:OpenHeosControl,代码行数:40,代码来源:SsdpClient.java

示例9: SSDPSocket

import java.net.MulticastSocket; //导入方法依赖的package包/类
public SSDPSocket(Context context) throws IOException {
        this.context = context;

        InetAddress localInAddress = InetAddress.getLocalHost();

        mSSDPMulticastGroup = new InetSocketAddress(SSDP.ADDRESS, SSDP.PORT);
        mLocalSocket = new MulticastSocket();
        mNetIf = NetworkInterface.getByInetAddress(localInAddress);

        mLocalSocket.joinGroup(mSSDPMulticastGroup, mNetIf);

//        mLocalSocket = new DatagramSocket(SSDP.PORT);
//        mLocalSocket.setBroadcast(true);
        mLocalSocket.setSoTimeout(TIMEOUT_MS);
    }
 
开发者ID:ayvazj,项目名称:rokontrol-android,代码行数:16,代码来源:SSDPSocket.java

示例10: OioDatagramChannel

import java.net.MulticastSocket; //导入方法依赖的package包/类
/**
 * Create a new instance from the given {@link MulticastSocket}.
 *
 * @param socket    the {@link MulticastSocket} which is used by this instance
 */
public OioDatagramChannel(MulticastSocket socket) {
    super(null);

    boolean success = false;
    try {
        socket.setSoTimeout(SO_TIMEOUT);
        socket.setBroadcast(false);
        success = true;
    } catch (SocketException e) {
        throw new ChannelException(
                "Failed to configure the datagram socket timeout.", e);
    } finally {
        if (!success) {
            socket.close();
        }
    }

    this.socket = socket;
    config = new DefaultDatagramChannelConfig(this, socket);
}
 
开发者ID:wuyinxian124,项目名称:netty4.0.27Learn,代码行数:26,代码来源:OioDatagramChannel.java

示例11: 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

示例12: 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

示例13: 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

示例14: recvData

import java.net.MulticastSocket; //导入方法依赖的package包/类
/**
 * Blocking call
 */
public static boolean recvData(MulticastSocket s, byte[] buffer) throws IOException {
    s.setSoTimeout(100);
    // Create a DatagramPacket and do a receive
    final DatagramPacket pack = new DatagramPacket(buffer, buffer.length);
    try {
        s.receive(pack);
    } catch (SocketTimeoutException e) {
        return false;
    }
    // We have finished receiving data
    return true;
}
 
开发者ID:phishman3579,项目名称:Bitcoin,代码行数:16,代码来源:Multicast.java

示例15: UPnPSocket

import java.net.MulticastSocket; //导入方法依赖的package包/类
UPnPSocket(InetAddress deviceIp) throws IOException {
	Log.e(TAG, "UPnPSocket");

	mMulticastGroup = new InetSocketAddress(MULTICAST_ADDRESS, PORT);
	mMultiSocket = new MulticastSocket(new InetSocketAddress(deviceIp, 0));

	mMultiSocket.setSoTimeout(MSG_TIMEOUT);
}
 
开发者ID:dgmltn,项目名称:Android-UPnP-Browser,代码行数:9,代码来源:UPnPDeviceFinder.java


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