下面列出了java.net.ServerSocket#isClosed ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void run() {
while (true) {
ServerSocket serverSocket = Socks5Proxy.this.serverSocket;
if (serverSocket == null || serverSocket.isClosed() || Thread.currentThread().isInterrupted()) {
return;
}
// accept connection
Socket socket = null;
try {
socket = serverSocket.accept();
// initialize connection
establishConnection(socket);
} catch (SmackException | IOException e) {
// Do nothing, if caused by closing the server socket, thread will terminate in next loop.
LOGGER.log(Level.FINE, "Exception while " + Socks5Proxy.this + " was handling connection", e);
CloseableUtil.maybeClose(socket, LOGGER);
}
}
}
@Override
public void run() {
try {
server = new ServerSocket(port);
Socket client;
while (!isClosed) {
if (server.isClosed()) return;
client = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String msg;
while ((msg = in.readLine()) != null) {
content.add(msg.trim());
}
}
} catch (IOException e) {
if (!(e instanceof SocketException)) {
e.printStackTrace();
}
}
}
protected void start(InetAddress bind_addr, int port) throws Exception {
srv_sock=new ServerSocket(port, 50, bind_addr);
System.out.printf("%s listening on %s\n", EchoServer.class.getSimpleName(), srv_sock.getLocalSocketAddress());
while(!srv_sock.isClosed()) {
try {
Socket client_sock=srv_sock.accept();
ConnectionHandler handler=new ConnectionHandler(client_sock);
thread_pool.execute(handler);
}
catch(Throwable t) {
t.printStackTrace();
}
}
thread_pool.shutdown();
thread_pool.awaitTermination(3, TimeUnit.SECONDS);
}
private void close(final ServerSocket socket) {
try {
if (!socket.isClosed()) {
socket.close();
}
} catch (final IOException e) {
LOG.warn("Problem closing unresponsive socket {}", socket.getInetAddress(), e);
}
}
/**
* 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();
}
}
}
/**
* 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();
}
}
}
@Override
public void close() throws IOException {
ServerSocket local = serverSocket;
if (local != null && !local.isClosed()) {
local.close();
}
}
@Override
public void run() {
LOGGER.debug("Proxy shutdown starting...");
shutdown.set(true);
try {
if (!service.isShutdown()) {
service.shutdown();
}
for (Future<?> f : futures) {
f.cancel(true);
}
final ServerSocket serverSocket = socketRef.get();
if (!serverSocket.isClosed()) {
serverSocket.close();
}
for (Socket socket : sockets) {
try {
socket.close();
} catch (IOException ignored) {
// if we get an exception trying to close one socket swallow it and move onto the next one
}
}
LOGGER.debug("Proxy shutdown complete");
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
shutdownCountDownLatch.countDown();
}
}
/**
* Regression test for Harmony-1947.
*/
public void test_finishConnect() throws Exception {
SocketAddress address = new InetSocketAddress("localhost", 0);
ServerSocketChannel theServerChannel = ServerSocketChannel.open();
ServerSocket serversocket = theServerChannel.socket();
serversocket.setReuseAddress(true);
// Bind the socket
theServerChannel.socket().bind(address);
boolean doneNonBlockingConnect = false;
// Loop so that we make sure we're definitely testing finishConnect()
while (!doneNonBlockingConnect) {
channel1 = SocketChannel.open();
// Set the SocketChannel to non-blocking so that connect(..) does
// not block
channel1.configureBlocking(false);
boolean connected = channel1.connect(new InetSocketAddress("localhost",serversocket.getLocalPort()));
if (!connected) {
// Now set the SocketChannel back to blocking so that
// finishConnect() blocks.
channel1.configureBlocking(true);
doneNonBlockingConnect = channel1.finishConnect();
}
if (doneNonBlockingConnect) {
tryFinish();
}
channel1.close();
}
if (!serversocket.isClosed()) {
serversocket.close();
}
}
public static final void closeSocket(final ServerSocket pServerSocket) {
if(pServerSocket != null && !pServerSocket.isClosed()) {
try {
pServerSocket.close();
} catch (final IOException e) {
Debug.e(e);
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
String user = serverFrame.getHighlightedLime();
String time = getLiMeTime();
try {
switch (e.getActionCommand()) {
case SERVER_ACTION_START:
// START Server
cachedThreadPool = Executors.newCachedThreadPool();
cachedThreadPool.execute(serverModel);
break;
case SERVER_ACTION_STOP:
// STOP Server
ServerSocket serverSocket = serverModel.getServerSocket();
if (serverSocket != null && !serverSocket.isClosed()) {
serverSocket.close();
}
cachedThreadPool.shutdownNow();
break;
case SERVER_ACTION_KICK:
serverModel.sendSeedStatus(user, ERROR_ADMIN_KICKED);
// log UI
serverFrame.appendLog("[" + time + "]\n< " + user + " > is KICKED.\n");
break;
case SERVER_ACTION_BAN:
serverModel.sendSeedStatus(user, ERROR_ADMIN_BANNED);
// Ban User in database
serverModel.ban(user);
// log UI
serverFrame.appendLog("[" + time + "]\n< " + user + " > is BANNED.\n");
break;
case SERVER_ACTION_CLEAR_LOG:
serverFrame.clearLog();
break;
case SERVER_ACTION_CLEAR_HISTORY:
serverFrame.clearHistory();
break;
default:
limeInternalError(this.getClass().getCanonicalName(), e.getActionCommand());
break;
}
} catch (IOException | SQLException ex) {
ex.printStackTrace();
limeInternalError(this.getClass().getCanonicalName(), ex.getMessage());
}
}
/**
* 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();
}
/**
* 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();
}
/**
* 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();
registerConnection(finalAccept);
finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
final InputStream inputStream = finalAccept.getInputStream();
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, finalAccept.getInetAddress());
while (!finalAccept.isClosed()) {
session.execute();
}
} catch (Exception e) {
// When the socket is closed by the client, we throw our own SocketException
// to break the "keep alive" loop above.
if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) {
e.printStackTrace();
}
} finally {
safeClose(outputStream);
safeClose(inputStream);
safeClose(finalAccept);
unRegisterConnection(finalAccept);
}
}
});
} catch (IOException e) {
}
} while (!myServerSocket.isClosed());
}
});
myThread.setDaemon(true);
myThread.setName("NanoHttpd Main Listener");
myThread.start();
}
/**
* 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();
registerConnection(finalAccept);
finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
final InputStream inputStream = finalAccept.getInputStream();
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, finalAccept.getInetAddress());
while (!finalAccept.isClosed()) {
session.execute();
}
} catch (Exception e) {
// When the socket is closed by the client, we throw our own SocketException
// to break the "keep alive" loop above.
if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) {
e.printStackTrace();
}
} finally {
safeClose(outputStream);
safeClose(inputStream);
safeClose(finalAccept);
unRegisterConnection(finalAccept);
}
}
});
} catch (IOException e) {
}
} while (!myServerSocket.isClosed());
}
});
myThread.setDaemon(true);
myThread.setName("NanoHttpd Main Listener");
myThread.start();
}
/**
* 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();
registerConnection(finalAccept);
finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
final InputStream inputStream = finalAccept.getInputStream();
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, finalAccept.getInetAddress());
while (!finalAccept.isClosed()) {
session.execute();
}
} catch (Exception e) {
// When the socket is closed by the client, we throw our own SocketException
// to break the "keep alive" loop above.
if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) {
e.printStackTrace();
}
} finally {
safeClose(outputStream);
safeClose(inputStream);
safeClose(finalAccept);
unRegisterConnection(finalAccept);
}
}
});
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
} while (!myServerSocket.isClosed());
}
});
myThread.setDaemon(true);
myThread.setName("NanoHttpd Main Listener");
myThread.start();
}
/**
* Stops tcp test thread
* @throws IOException IOException
*/
private void stopTcpThreads() throws IOException {
for (ServerSocket srvSock: srvSocks)
if (!srvSock.isClosed())
srvSock.close();
}
/**
* 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();
registerConnection(finalAccept);
finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
final InputStream inputStream = finalAccept.getInputStream();
if (inputStream == null) {
safeClose(finalAccept);
unRegisterConnection(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, finalAccept.getInetAddress());
while (!finalAccept.isClosed()) {
session.execute();
}
} catch (Exception e) {
// When the socket is closed by the client, we throw our own SocketException
// to break the "keep alive" loop above.
if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) {
e.printStackTrace();
}
} finally {
safeClose(outputStream);
safeClose(inputStream);
safeClose(finalAccept);
unRegisterConnection(finalAccept);
}
}
});
}
} catch (IOException e) {
}
} while (!myServerSocket.isClosed());
}
});
myThread.setDaemon(true);
myThread.setName("NanoHttpd Main Listener");
myThread.start();
}
@Override
public void run()
{
this.running = true;
try
{
server = new ServerSocket(getPort());
server.setReuseAddress(true);
if (!server.isBound())
{
server.bind(new InetSocketAddress(getPort()));
}
if (!server.isClosed())
{
client = server.accept();
client.setTcpNoDelay(true);
output = new ObjectOutputStream(client.getOutputStream());
output.flush();
}
} catch (IOException e)
{
e.printStackTrace();
}
//connected
if (client != null)
{
final short sensitivity = AppSettings.getInstance().getSystemSettings().getMouseSensitivity();
if (AppSettings.getInstance().getSettingsElements().getPositioningMode() == PositioningMode.ABSOLUTE)
{
AppSettings.getInstance().getConnectionManager()
.getUsbConnectionManager()
.send(PositioningMode.ABSOLUTE, sensitivity);
} else
{
AppSettings.getInstance().getConnectionManager().getUsbConnectionManager().send(
PositioningMode.RELATIVE, sensitivity);
}
SettingsActivity.getActivity().startActivity(
AppSettings.getInstance().getActivitySettings()
.getCanvasIntent()); // Load the Canvas
}
}
/**
* 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();
registerConnection(finalAccept);
finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
final InputStream inputStream = finalAccept
.getInputStream();
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, finalAccept
.getInetAddress());
while (!finalAccept.isClosed()) {
session.execute();
}
} catch (Exception e) {
// When the socket is closed by the client,
// we throw our own SocketException
// to break the "keep alive" loop above.
if (!(e instanceof SocketException && "NanoHttpd Shutdown"
.equals(e.getMessage()))) {
e.printStackTrace();
}
} finally {
safeClose(outputStream);
safeClose(inputStream);
safeClose(finalAccept);
unRegisterConnection(finalAccept);
}
}
});
} catch (IOException e) {
}
} while (!myServerSocket.isClosed());
}
});
myThread.setDaemon(true);
myThread.setName("NanoHttpd Main Listener");
myThread.start();
}