本文整理匯總了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);
}
}
示例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(" %*");
}
}
}
示例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});
}
示例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;
}
}
示例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();
}
}
}
示例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());
}
示例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();
}
}
}
示例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;
}
}
示例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();
}
}
示例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) { }
}
示例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();
}
}
}
示例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){}
}
示例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();
}
示例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);
}
示例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();
}