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


Java ServerSocket.isClosed方法代码示例

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


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

示例1: stopListening

import java.net.ServerSocket; //导入方法依赖的package包/类
/**
 * Stop the listener
 */
public void stopListening(ListenKey listener) throws IOException {
    if (!(listener instanceof SocketListenKey)) {
        throw new IllegalArgumentException("Invalid listener");
    }

    synchronized (listener) {
        ServerSocket ss = ((SocketListenKey)listener).socket();

        // if the ServerSocket has been closed it means
        // the listener is invalid
        if (ss.isClosed()) {
            throw new IllegalArgumentException("Invalid listener");
        }
        ss.close();
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:20,代码来源:SocketTransportService.java

示例2: closeSilently

import java.net.ServerSocket; //导入方法依赖的package包/类
/** close things if not null, for use in finally blocks, swallows exceptions */
public static void closeSilently(final ServerSocket socket) {
    if (socket != null && !socket.isClosed()) {
        try {
            socket.close();
        } catch (IOException e) {
            // silence
        }
    }
}
 
开发者ID:archos-sa,项目名称:aos-FileCoreLibrary,代码行数:11,代码来源:IOUtils.java

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

示例4: closeServerSocket_do

import java.net.ServerSocket; //导入方法依赖的package包/类
/**
 * Closes the specified ServerSocket
 */
protected boolean closeServerSocket_do(ServerSocket socket, boolean removeFromList)
{
    this.logDebug("closeSocket: " + socket);

    if (null == socket)
    {
        return false;
    }
    else
    {
        boolean flag = false;

        try
        {
            if (!socket.isClosed())
            {
                socket.close();
                flag = true;
            }
        }
        catch (IOException ioexception)
        {
            this.logWarning("IO: " + ioexception.getMessage());
        }

        if (removeFromList)
        {
            this.serverSocketList.remove(socket);
        }

        return flag;
    }
}
 
开发者ID:Notoh,项目名称:DecompiledMinecraft,代码行数:37,代码来源:RConThreadBase.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:lamsfoundation,项目名称:lams,代码行数:43,代码来源:JSSESocketFactory.java

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

示例7: closeServerSocket

import java.net.ServerSocket; //导入方法依赖的package包/类
public static void closeServerSocket(ServerSocket socket) {
	if (socket != null && !socket.isClosed()) {
		try {
			socket.close();
		} catch (IOException e) {
			DLog.e(e);
		}
	}
}
 
开发者ID:youmi,项目名称:nativead,代码行数:10,代码来源:IOUtils.java

示例8: start

import java.net.ServerSocket; //导入方法依赖的package包/类
/**
 * Starts the server
 * <p/>
 * Throws an IOException if the socket is already in use
 */
public void start() throws IOException {
    Log.i("NanoHTTPD", "server start");
    myServerSocket = new ServerSocket();
    myServerSocket.bind((hostname != null) ? new InetSocketAddress(
            hostname, myPort) : new InetSocketAddress(myPort));

    myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            do {
                try {
                    final Socket finalAccept = myServerSocket.accept();
                    Log.i("NanoHTTPD",
                            "accept request from "
                                    + finalAccept.getInetAddress());
                    InputStream inputStream = finalAccept.getInputStream();
                    OutputStream outputStream = finalAccept
                            .getOutputStream();
                    TempFileManager tempFileManager = tempFileManagerFactory
                            .create();
                    final HTTPSession session = new HTTPSession(
                            tempFileManager, inputStream, outputStream);
                    asyncRunner.exec(new Runnable() {
                        @Override
                        public void run() {
                            session.run();
                            if (finalAccept != null) {
                                try {
                                    finalAccept.close();
                                } catch (IOException ignored) {
                                }
                            }
                        }
                    });
                } catch (IOException e) {
                }
            } while (!myServerSocket.isClosed());
        }
    });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:49,代码来源:NanoHTTPD.java

示例9: JNetSimpleServerSecure

import java.net.ServerSocket; //导入方法依赖的package包/类
/**
 * Binds the server to a specified port and process requests with the
 * handler (encrypted)
 *
 * @param port Server port to bind
 * @param handler Handler to process requests
 */
public JNetSimpleServerSecure(int port, JNetSimpleHandler handler) {
    this.handler = handler;

    try {
        serverSocket = new ServerSocket(port, Integer.MAX_VALUE);

        thread = new Thread(() -> {
            while (!serverSocket.isClosed()) {
                try {
                    Socket socket = serverSocket.accept();
                    socket.setKeepAlive(true);

                    executor.submit(() -> {
                        ObjectInputStream in = null;
                        ObjectOutputStream out = null;

                        try {
                            in = new ObjectInputStream(socket.getInputStream());
                            out = new ObjectOutputStream(socket.getOutputStream());

                            KeyPair keyPair = Crypter.generateKeyPair();
                            PublicKey publicKey = (PublicKey) in.readObject();

                            out.writeObject(keyPair.getPublic());

                            SecretKey key = Crypter.generateEC(keyPair.getPrivate(), publicKey);

                            byte[] decryptedObject = Crypter.decrypt((byte[]) in.readObject(), key);
                            Object object = Crypter.toObject(decryptedObject);

                            byte[] byteResponse = Crypter.toByteArray(this.handler.process(object));
                            byte[] encryptedResponse = Crypter.encrypt(byteResponse, key);

                            out.writeObject(encryptedResponse);
                            out.flush();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        } finally {
                            try {
                                if (in != null) {
                                    in.close();
                                }

                                if (out != null) {
                                    out.close();
                                }

                                if (!socket.isClosed()) {
                                    socket.close();
                                }
                            } catch (IOException ex) {
                                ex.printStackTrace();
                            }
                        }
                    });
                } catch (IOException ex) {
                    if (!ex.getMessage().toLowerCase().contains("socket closed")) {
                        ex.printStackTrace();
                    }
                }
            }
        });
        thread.start();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
 
开发者ID:NexusByte,项目名称:JNetSimple,代码行数:75,代码来源:JNetSimpleServerSecure.java

示例10: start

import java.net.ServerSocket; //导入方法依赖的package包/类
/**
 * Start the server.
 * 
 * @throws IOException if the socket is in use.
 */
public void start() throws IOException
{
	myServerSocket = new ServerSocket();
	myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));

	myThread = new Thread(new Runnable()
	{
		@Override
		public void run()
		{
			do
			{
				try
				{
					final Socket finalAccept = myServerSocket.accept();
					final InputStream inputStream = finalAccept.getInputStream();
					if (inputStream == null)
					{
						safeClose(finalAccept);
					}
					else
					{
						asyncRunner.exec(new Runnable()
						{
							@Override
							public void run()
							{
								OutputStream outputStream = null;
								try
								{
									outputStream = finalAccept.getOutputStream();
									TempFileManager tempFileManager = tempFileManagerFactory.create();
									HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream);
									while (!finalAccept.isClosed())
									{
										session.execute();
									}
								}
								catch (IOException e)
								{
									e.printStackTrace();
								}
								finally
								{
									safeClose(outputStream);
									safeClose(inputStream);
									safeClose(finalAccept);
								}
							}
						});
					}
				}
				catch (IOException e)
				{
				}
			}
			while (!myServerSocket.isClosed());
		}
	});
	myThread.setDaemon(true);
	myThread.setName("NanoHttpd Main Listener");
	myThread.start();
}
 
开发者ID:nwpu043814,项目名称:AspriseOCR,代码行数:69,代码来源:NanoHTTPD.java

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

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