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


Java ServerSocket.setSoTimeout方法代码示例

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


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

示例1: await

import java.net.ServerSocket; //导入方法依赖的package包/类
public static TargetMonitor await(int port) {
    try {
        final ServerSocket serverSocket = new ServerSocket(port);
        serverSocket.setSoTimeout(ACCEPT_TIMEOUT_MILLIS);
        serverSocket.setReuseAddress(true);
        final Socket socket = serverSocket.accept();
        return new TargetMonitor(new PrintStream(socket.getOutputStream())) {
            @Override public void close() throws IOException {
                socket.close();
                serverSocket.close();
            }
        };

    } catch (IOException e) {
        throw new RuntimeException("Failed to accept a monitor on localhost:" + port, e);
    }
}
 
开发者ID:dryganets,项目名称:vogar,代码行数:18,代码来源:TargetMonitor.java

示例2: setUpExternalEditorTest

import java.net.ServerSocket; //导入方法依赖的package包/类
@BeforeClass
public static void setUpExternalEditorTest() throws IOException {
    listener = new ServerSocket(0);
    listener.setSoTimeout(30000);
    int localPort = listener.getLocalPort();

    executionScript = Paths.get(isWindows() ? "editor.bat" : "editor.sh").toAbsolutePath();
    Path java = Paths.get(System.getProperty("java.home")).resolve("bin").resolve("java");
    try (BufferedWriter writer = Files.newBufferedWriter(executionScript)) {
        if(!isWindows()) {
            writer.append(java.toString()).append(" ")
                    .append(" -cp ").append(System.getProperty("java.class.path"))
                    .append(" CustomEditor ").append(Integer.toString(localPort)).append(" [email protected]");
            executionScript.toFile().setExecutable(true);
        } else {
            writer.append(java.toString()).append(" ")
                    .append(" -cp ").append(System.getProperty("java.class.path"))
                    .append(" CustomEditor ").append(Integer.toString(localPort)).append(" %*");
        }
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:22,代码来源:ExternalEditorTest.java

示例3: start

import java.net.ServerSocket; //导入方法依赖的package包/类
public void start() throws IOException {
    logger.debug("Starting Bootstrap Listener to communicate with Bootstrap Port {}", bootstrapPort);

    serverSocket = new ServerSocket();
    serverSocket.bind(new InetSocketAddress("localhost", 0));
    serverSocket.setSoTimeout(2000);

    final int localPort = serverSocket.getLocalPort();
    logger.info("Started Bootstrap Listener, Listening for incoming requests on port {}", localPort);

    listener = new Listener(serverSocket);
    final Thread listenThread = new Thread(listener);
    listenThread.setDaemon(true);
    listenThread.setName("Listen to Bootstrap");
    listenThread.start();

    logger.debug("Notifying Bootstrap that local port is {}", localPort);
    sendCommand("PORT", new String[] { String.valueOf(localPort), secretKey});
}
 
开发者ID:apache,项目名称:nifi-registry,代码行数:20,代码来源:BootstrapListener.java

示例4: serveOne

import java.net.ServerSocket; //导入方法依赖的package包/类
private void serveOne() {
    try {
        ServerSocket serverSocket = new ServerSocket();
        serverSocket.setReuseAddress(true);
        serverSocket.setSoTimeout(SERVER_SOCKET_TIMEOUT_IN_MILLISECONDS);
        serverSocket.bind(new InetSocketAddress(HOST, PORT));

        acceptLatch.countDown();

        // accept a new client
        Socket clientSocket = serverSocket.accept();

        if (config.closeConnectionAfterAccept) {
            clientSocket.close();
            serverSocket.close();
            return;
        }

        // read data from client
        byte[] dataReceived = new byte[config.messageSentToServer.getBytes().length];
        int read = 0;
        do {
            read += clientSocket.getInputStream().read(dataReceived, read, dataReceived.length - read);
        } while (read < dataReceived.length);
        messageReceivedByServer = dataReceived;

        // write data back to client
        clientSocket.getOutputStream().write(dataReceived);

        clientSocket.close();
        serverSocket.close();

    } catch(IOException e) {
        exceptionEncounteredDuringServe = e;
    }
}
 
开发者ID:cpppwner,项目名称:NoRiskNoFun,代码行数:37,代码来源:TCPClientSocketImplTests.java

示例5: checkConfig

import java.net.ServerSocket; //导入方法依赖的package包/类
/**
 * Checks that the certificate is compatible with the enabled cipher suites.
 * If we don't check now, the JIoEndpoint can enter a nasty logging loop.
 * See bug 45528.
 */
private void checkConfig() throws IOException {
    // Create an unbound server socket
    ServerSocket socket = sslProxy.createServerSocket();
    initServerSocket(socket);

    try {
        // Set the timeout to 1ms as all we care about is if it throws an
        // SSLException on accept.
        socket.setSoTimeout(1);

        socket.accept();
        // Will never get here - no client can connect to an unbound port
    } catch (SSLException ssle) {
        // SSL configuration is invalid. Possibly cert doesn't match ciphers
        IOException ioe = new IOException(sm.getString(
                "jsse.invalid_ssl_conf", ssle.getMessage()));
        ioe.initCause(ssle);
        throw ioe;
    } catch (Exception e) {
        /*
         * Possible ways of getting here
         * socket.accept() throws a SecurityException
         * socket.setSoTimeout() throws a SocketException
         * socket.accept() throws some other exception (after a JDK change)
         *      In these cases the test won't work so carry on - essentially
         *      the behaviour before this patch
         * socket.accept() throws a SocketTimeoutException
         *      In this case all is well so carry on
         */
    } finally {
        // Should be open here but just in case
        if (!socket.isClosed()) {
            socket.close();
        }
    }

}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:43,代码来源:JSSESocketFactory.java

示例6: setProperties

import java.net.ServerSocket; //导入方法依赖的package包/类
public void setProperties(ServerSocket socket) throws SocketException{
    if (rxBufSize != null)
        socket.setReceiveBufferSize(rxBufSize.intValue());
    if (performanceConnectionTime != null && performanceLatency != null &&
            performanceBandwidth != null)
        socket.setPerformancePreferences(
                performanceConnectionTime.intValue(),
                performanceLatency.intValue(),
                performanceBandwidth.intValue());
    if (soReuseAddress != null)
        socket.setReuseAddress(soReuseAddress.booleanValue());
    if (soTimeout != null && soTimeout.intValue() >= 0)
        socket.setSoTimeout(soTimeout.intValue());
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:15,代码来源:SocketProperties.java

示例7: checkConfig

import java.net.ServerSocket; //导入方法依赖的package包/类
/**
 * Checks that the certificate is compatible with the enabled cipher suites.
 * If we don't check now, the JIoEndpoint can enter a nasty logging loop.
 * See bug 45528.
 */
private void checkConfig() throws IOException {
    // Create an unbound server socket
    ServerSocket socket = sslProxy.createServerSocket();
    initServerSocket(socket);

    try {
        // Set the timeout to 1ms as all we care about is if it throws an
        // SSLException on accept. 
        socket.setSoTimeout(1);

        socket.accept();
        // Will never get here - no client can connect to an unbound port
    } catch (SSLException ssle) {
        // SSL configuration is invalid. Possibly cert doesn't match ciphers
        IOException ioe = new IOException(sm.getString(
                "jsse.invalid_ssl_conf", ssle.getMessage()));
        ioe.initCause(ssle);
        throw ioe;
    } catch (Exception e) {
        /*
         * Possible ways of getting here
         * socket.accept() throws a SecurityException
         * socket.setSoTimeout() throws a SocketException
         * socket.accept() throws some other exception (after a JDK change)
         *      In these cases the test won't work so carry on - essentially
         *      the behaviour before this patch
         * socket.accept() throws a SocketTimeoutException
         *      In this case all is well so carry on
         */
    } finally {
        // Should be open here but just in case
        if (!socket.isClosed()) {
            socket.close();
        }
    }
    
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:43,代码来源:JSSESocketFactory.java

示例8: newServerSocket

import java.net.ServerSocket; //导入方法依赖的package包/类
static synchronized ServerSocket newServerSocket() throws IOException {
    if (_sockets.isEmpty() && _outstandingSockets > PseudoServer.getWaitThreshhold()) {
        try { synchronized( _releaseSemaphore) {_releaseSemaphore.wait( PseudoServer.getSocketReleaseWaitTime() ); } } catch (InterruptedException e) {};
    }
    _outstandingSockets++;
    if (!_sockets.isEmpty()) {
        return (ServerSocket) _sockets.remove(0);
    } else {
        ServerSocket serverSocket = new ServerSocket(0);
        serverSocket.setSoTimeout( 1000 );
        return serverSocket;
    }
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:14,代码来源:PseudoServer.java

示例9: test

import java.net.ServerSocket; //导入方法依赖的package包/类
void test(String method) throws Exception {
    ss = new ServerSocket(0);
    ss.setSoTimeout(ACCEPT_TIMEOUT);
    int port = ss.getLocalPort();

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

    try {
        URL url = new URL("http://localhost:" + port + "/");
        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setDoOutput(true);
        if (method != null)
            uc.setRequestMethod(method);
        uc.setChunkedStreamingMode(4096);
        OutputStream os = uc.getOutputStream();
        os.write("Hello there".getBytes());

        InputStream is = uc.getInputStream();
        is.close();
    } catch (IOException expected) {
        //expected.printStackTrace();
    } finally {
        ss.close();
        otherThread.join();
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:28,代码来源:StreamingRetry.java

示例10: main

import java.net.ServerSocket; //导入方法依赖的package包/类
public static void main(String [] args) throws IOException, FileNotFoundException {

        //The bug 8021820 is a Mac specific and because of that test will pass on all
        //other platforms
        if (!System.getProperty("os.name").contains("OS X")) {
           return;
        }

        //Create test directory with test files
        prepareTestEnv();

        //Consume FD ids for this java process to overflow the 1024
        openFiles(FDTOOPEN,new File(TESTFILE));

        //Wait for incoming connection and make the select() used in java.net
        //classes fail the limitation on FDSET_SIZE
        ServerSocket socket = new ServerSocket(0);

        //Set the minimal timeout, no one is
        //going to connect to this server socket
        socket.setSoTimeout(1);

        // The accept() call will throw SocketException if the
        // select() has failed due to limitation on fds size,
        // indicating test failure. A SocketTimeoutException
        // is expected, so it is caught and ignored, and the test
        // passes.
        try {
           socket.accept();
        } catch (SocketTimeoutException e) { }
    }
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:32,代码来源:SelectFdsLimit.java

示例11: checkConfig

import java.net.ServerSocket; //导入方法依赖的package包/类
/**
 * Checks that the certificate is compatible with the enabled cipher suites.
 * If we don't check now, the JIoEndpoint can enter a nasty logging loop.
 * See bug 45528.
 */
private void checkConfig() throws IOException {
	// Create an unbound server socket
	ServerSocket socket = sslProxy.createServerSocket();
	initServerSocket(socket);

	try {
		// Set the timeout to 1ms as all we care about is if it throws an
		// SSLException on accept.
		socket.setSoTimeout(1);

		socket.accept();
		// Will never get here - no client can connect to an unbound port
	} catch (SSLException ssle) {
		// SSL configuration is invalid. Possibly cert doesn't match ciphers
		IOException ioe = new IOException(sm.getString("jsse.invalid_ssl_conf", ssle.getMessage()));
		ioe.initCause(ssle);
		throw ioe;
	} catch (Exception e) {
		/*
		 * Possible ways of getting here socket.accept() throws a
		 * SecurityException socket.setSoTimeout() throws a SocketException
		 * socket.accept() throws some other exception (after a JDK change)
		 * In these cases the test won't work so carry on - essentially the
		 * behaviour before this patch socket.accept() throws a
		 * SocketTimeoutException In this case all is well so carry on
		 */
	} finally {
		// Should be open here but just in case
		if (!socket.isClosed()) {
			socket.close();
		}
	}

}
 
开发者ID:how2j,项目名称:lazycat,代码行数:40,代码来源:JSSESocketFactory.java

示例12: IdentServer

import java.net.ServerSocket; //导入方法依赖的package包/类
public IdentServer(String login)
{
	this.login = login;
	try
	{
		socket = new ServerSocket(113);
		socket.setSoTimeout(60000);
		new Thread(this).start();
	}
	catch (Exception e){}
}
 
开发者ID:Esri,项目名称:defense-solutions-proofs-of-concept,代码行数:12,代码来源:IdentServer.java

示例13: PortForwarder

import java.net.ServerSocket; //导入方法依赖的package包/类
public PortForwarder(int from, int to) throws IOException {
    this.to = to;
    serverSocket = new ServerSocket(from);
    serverSocket.setSoTimeout(30000);
    this.start();
}
 
开发者ID:maoling,项目名称:fuck_zookeeper,代码行数:7,代码来源:PortForwarder.java

示例14: accept

import java.net.ServerSocket; //导入方法依赖的package包/类
/**
 * Accept a connection from a debuggee and handshake with it.
 */
public Connection accept(ListenKey listener, long acceptTimeout, long handshakeTimeout) throws IOException {
    if (acceptTimeout < 0 || handshakeTimeout < 0) {
        throw new IllegalArgumentException("timeout is negative");
    }
    if (!(listener instanceof SocketListenKey)) {
        throw new IllegalArgumentException("Invalid listener");
    }
    ServerSocket ss;

    // obtain the ServerSocket from the listener - if the
    // socket is closed it means the listener is invalid
    synchronized (listener) {
        ss = ((SocketListenKey)listener).socket();
        if (ss.isClosed()) {
           throw new IllegalArgumentException("Invalid listener");
        }
    }

    // from here onwards it's possible that the ServerSocket
    // may be closed by a call to stopListening - that's okay
    // because the ServerSocket methods will throw an
    // IOException indicating the socket is closed.
    //
    // Additionally, it's possible that another thread calls accept
    // with a different accept timeout - that creates a same race
    // condition between setting the timeout and calling accept.
    // As it is such an unlikely scenario (requires both threads
    // to be using the same listener we've chosen to ignore the issue).

    ss.setSoTimeout((int)acceptTimeout);
    Socket s;
    try {
        s = ss.accept();
    } catch (SocketTimeoutException x) {
        throw new TransportTimeoutException("timeout waiting for connection");
    }

    // handshake here
    handshake(s, handshakeTimeout);

    return new SocketConnection(s);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:46,代码来源:SocketTransportService.java

示例15: startWebServer

import java.net.ServerSocket; //导入方法依赖的package包/类
/**
 * запуск вэбсервера
 *
 * @param port На каком порту
 */
synchronized public void startWebServer(int port) {
    if (!isActive) {
        isActive = true;
    } else {
        return;
    }

    // привинтить сокет на локалхост, порт port
    QLog.l().logger().info("Отчетный сервер захватывает порт \"" + port + "\".");
    try {
        reportSocket = new ServerSocket(port, 0);
    } catch (Exception e) {
        throw new ReportException("Ошибка при создании серверного сокета для вэбсервера: " + e);
    }
    // поток вэбсервера, весит параллельно и обслуживает запросы
    webTread = new Thread() {

        public WebServer webServer;

        @Override
        public void run() {
            System.out.println("Report server for QSystem started.");
            QLog.l().logRep().info("Отчетный вэбсервер системы 'Очередь' запущен.");
            try {
                reportSocket.setSoTimeout(500);
            } catch (SocketException ex) {
            }
            while (isActive && !webTread.isInterrupted()) {
                // ждём нового подключения, после чего запускаем обработку клиента
                // в новый вычислительный поток и увеличиваем счётчик на единичку
                final Socket socket;
                try {
                    socket = reportSocket.accept();
                    final RunnableSocket rs = new RunnableSocket();
                    rs.setSocket(socket);
                    final Thread thread = new Thread(rs);
                    thread.start();
                } catch (SocketTimeoutException ex) {
                } catch (IOException ex) {
                    throw new ReportException("Ошибка при работе сокета для вэбсервера: " + ex);
                }
            }
            try {
                if (reportSocket != null && !reportSocket.isClosed()) {
                    reportSocket.close();
                }
            } catch (IOException ex) {
            }
            QLog.l().logRep().info("Отчетный вэбсервер системы 'Очередь' остановлен.");

        }
    };
    // и запускаем новый вычислительный поток (см. ф-ю run())
    webTread.setDaemon(true);
    webTread.setPriority(Thread.NORM_PRIORITY);
    webTread.start();

}
 
开发者ID:bcgov,项目名称:sbc-qsystem,代码行数:64,代码来源:WebServer.java


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