List of usage examples for java.net Socket getInetAddress
public InetAddress getInetAddress()
From source file:de.kapsi.net.daap.bio.DaapServerBIO.java
/** * Accepts an incoming connection./*from w w w .ja va 2 s . co m*/ */ private boolean accept(Socket socket) throws IOException { if (filter != null && !filter.accept(socket.getInetAddress())) { if (LOG.isInfoEnabled()) { LOG.info("DaapFilter refused connection from " + socket); } return false; } DaapConnectionBIO connection = new DaapConnectionBIO(this, socket); Thread connThread = threadFactory.createDaapThread(connection, "DaapConnectionThread-" + (++threadNo)); connThread.start(); return true; }
From source file:de.xwic.appkit.core.cluster.impl.ClusterNodeClientProtocol.java
/** * Initiated by a remote node that wants to connect to this instance. * @param inMessage/*from www. j a v a2s . co m*/ * @return */ private Response onConnect(Socket socket, Message inMessage) { String remoteNodeName = inMessage.getArgument(); Integer[] data = (Integer[]) inMessage.getContainer(); int remotePort = data[0]; int internalNodeId = data[1]; int remoteMasterPriority = data[2]; NodeAddress nodeAddress = new NodeAddress(socket.getInetAddress().getHostAddress(), remotePort); log.debug( "Initial Connection Attempt from " + nodeAddress + ", identified as Node '" + remoteNodeName + "'"); remoteNode = (ClusterNode) cluster.getNodeByName(remoteNodeName); if (remoteNode == null) { // this is a node we do not have in our list. remoteNode = new ClusterNode(nodeAddress); remoteNode.setName(remoteNodeName); remoteNode.setMasterPriority(remoteMasterPriority); cluster.registerNode(remoteNode); } // open the channel back OutboundChannel oc = new OutboundChannel(cluster); try { log.debug("Attempt to open reversal connection to remote node '" + remoteNode + "'"); oc.openConnection(remoteNode, true, internalNodeId); } catch (NodeUnavailableException e) { log.error("Connection call-back failed.", e); return new Response(false, "Connection Failed " + e); } return null; }
From source file:net.wimpi.telnetd.net.ConnectionManager.java
/** * Method that that tries to connect an incoming request. * Properly queueing.// w w w . ja v a 2 s . c o m * * @param insock Socket thats representing the incoming connection. */ public void makeConnection(Socket insock) { log.debug("makeConnection()::" + insock.toString()); if (connectionFilter == null || (connectionFilter != null && connectionFilter.isAllowed(insock.getInetAddress()))) { //we create the connection data object at this point to //store certain information there. ConnectionData newCD = new ConnectionData(insock, this); newCD.setLoginShell(loginShell); newCD.setLineMode(lineMode); if (m_OpenConnections.size() < maxConnections) { //create a new Connection instance Connection con = new Connection(m_ThreadGroup, newCD); //log the newly created connection Object[] args = { new Integer(m_OpenConnections.size() + 1) }; log.info(MessageFormat.format("connection #{0,number,integer} made.", args)); //register it for being managed synchronized (m_OpenConnections) { m_OpenConnections.add(con); } //start it con.start(); } } else { log.info("makeConnection():: Active Filter blocked incoming connection."); try { insock.close(); } catch (IOException ex) { //do nothing or log. } } }
From source file:org.bml.util.server.BServer.java
/** * The runInvProxy class starts a new server socket and listens for * connections from clients. Upon recieving a connection, it starts a new * InvProxyThread to process the connection. * @param aPort The port to attach to// w w w . ja va 2 s .c o m * @param aNumThreads the number of worker threads * @param aSleepTime sleep time in between checks * @param aMaxQueueLength the max requests to queue up * @param accessLog a Log to write access info */ public void runInvProxy(int aPort, int aNumThreads, long aSleepTime, int aMaxQueueLength, Log accessLog) { this.accessLog = accessLog; if (LOG.isDebugEnabled()) { LOG.debug("Attempting to start server on port: " + aPort); } //Start Server ServerSocket myServerSocket = null; try { myServerSocket = new ServerSocket(aPort, aMaxQueueLength); } catch (IOException e) { System.out.println(e); return; } if (LOG.isDebugEnabled()) { LOG.debug("Server started on port: " + aPort); } //Continuously accept connections and start threads to //process connections. while (!theDone) { if (LOG.isDebugEnabled()) { LOG.debug("Ready to accept client connection"); } Socket myClientSocket = null; try { myClientSocket = myServerSocket.accept(); } catch (IOException e) { System.out.println("Accept Error: " + e); break; } if (LOG.isDebugEnabled()) { LOG.debug("Accepted connection from client: " + myClientSocket.getInetAddress() + "\nStarting thread to deal with connection"); } //Make sure there aren't too many active threads if (aNumThreads != -1) { while (Thread.activeCount() > aNumThreads) { if (LOG.isDebugEnabled()) { LOG.debug("Too many active threads. Waiting " + aSleepTime + "(ms) before trying to start new HitServerInvProxyThread again"); } try { Thread.sleep(aSleepTime); } catch (InterruptedException e) { System.out.println(e); break; } } } if (myClientSocket != null && myClientSocket.isConnected()) { new InvProxyThread(this, myClientSocket, this.accessLog); } else { if (LOG.isWarnEnabled()) { LOG.warn("Client Socket is null or not connected when starting thread"); } break; } } //Closing socket if (LOG.isDebugEnabled()) { LOG.debug("Closing server socket. In general, we should never get here."); } try { myServerSocket.close(); } catch (IOException e) { System.out.println(e); return; } }
From source file:edu.vt.middleware.gator.log4j.SocketServer.java
/** {@inheritDoc}. */ public void run() { while (serverSocket != null && serverSocket.isBound()) { logger.info("Waiting to accept a new client."); Socket socket = null; InetAddress inetAddress = null; try {/*from ww w . j a v a 2 s .c o m*/ socket = serverSocket.accept(); inetAddress = socket.getInetAddress(); // Validate newly-connected client if (eventHandlerMap.keySet().size() >= maxClients) { throw new UnauthorizedClientException(inetAddress, "Maximum number of clients exceeded."); } final ProjectConfig project = getProject(inetAddress); if (project == null) { throw new UnauthorizedClientException(inetAddress, "Client not registered with any projects."); } // Explicitly enable TCP keep alives to try to help reclaim resources // from dead clients socket.setKeepAlive(true); logger.info("Accepted connection from client " + inetAddress); logger.info("Configuring logger repository for " + inetAddress); final LoggerRepository repo = getLoggerRepository(project); configurator.configure(project, repo); logger.info("Logger repository configured successfully."); final LoggingEventHandler handler = new LoggingEventHandler(socket, repo, eventExecutor); handler.getSocketCloseListeners().add(this); eventHandlerMap.put(inetAddress, handler); handlerExecutor.execute(handler); } catch (UnauthorizedClientException e) { logger.warn(String.format("Unauthorized client %s rejected for reason: " + e.getMessage(), e.getClient())); if (socket != null && !socket.isClosed()) { logger.info("Closing socket for rejected host."); try { socket.close(); } catch (IOException ioex) { logger.error("Error closing client socket.", ioex); } } } catch (SocketException e) { // Check whether this is caused by a stop() invocation: // calling stop() closes server socket, which throws SocketException // from blocking accept() call if (serverSocket == null) { logger.info("Ignoring SocketException caused by stop() invocation."); } else { logger.error(e); } } catch (Exception e) { logger.error(e); } } }
From source file:edu.vt.middleware.gator.server.SocketServer.java
/** {@inheritDoc}. */ public void run() { while (serverSocket != null && serverSocket.isBound()) { logger.info("Waiting to accept a new client."); Socket socket = null; InetAddress inetAddress = null; try {/*from w w w . j a va 2s . c o m*/ socket = serverSocket.accept(); inetAddress = socket.getInetAddress(); // Validate newly-connected client if (eventHandlerMap.keySet().size() >= maxClients) { throw new UnauthorizedClientException(inetAddress, "Maximum number of clients exceeded."); } final ProjectConfig project = getProject(inetAddress); if (project == null) { throw new UnauthorizedClientException(inetAddress, "Client not registered with any projects."); } // Explicitly enable TCP keep alives to try to help reclaim resources // from dead clients socket.setKeepAlive(true); logger.info("Accepted connection from client " + inetAddress); logger.info("Configuring logger repository for " + inetAddress); final LoggingEngine engine = getLoggingEngine(project); if (engine != null) { engine.register(inetAddress, project); logger.info("Successfully configured " + engine); final LoggingEventHandler handler = new LoggingEventHandler(socket, engine, eventExecutor); handler.getSocketCloseListeners().add(this); eventHandlerMap.put(inetAddress, handler); handlerExecutor.execute(handler); } else { logger.warn(String.format("Logging engine not found for %s. Closing socket for %s.", project, inetAddress)); socket.close(); } } catch (UnauthorizedClientException e) { logger.warn(String.format("Unauthorized client %s rejected for reason: " + e.getMessage(), e.getClient())); if (socket != null && !socket.isClosed()) { logger.info("Closing socket for rejected host."); try { socket.close(); } catch (IOException ioex) { logger.error("Error closing client socket.", ioex); } } } catch (SocketException e) { // Check whether this is caused by a stop() invocation: // calling stop() closes server socket, which throws SocketException // from blocking accept() call if (serverSocket == null) { logger.info("Ignoring SocketException caused by stop() invocation."); } else { logger.error(e); } } catch (Exception e) { logger.error(e); } } }
From source file:org.psit.transwatcher.TransWatcher.java
private void startConnectionKeepAliveWatchDog(final Socket newImageListenerSocket) { watchDogThread = new Thread(new Runnable() { public void run() { try { while (true) { Thread.sleep(5000); InetSocketAddress addr = new InetSocketAddress(newImageListenerSocket.getInetAddress(), 80); Socket s = new Socket(); s.connect(addr, 1000); s.close();// w ww . j av a 2 s . co m notifyMessage("WatchDog ping."); } } catch (InterruptedException e) { notifyMessage("WatchDog interrupted"); } catch (IOException e) { notifyMessage("WatchDog: Connection to card lost."); try { newImageListenerSocket.close(); } catch (IOException e1) { e1.printStackTrace(); } e.printStackTrace(); } }; }, "ConnectionWatchDog"); watchDogThread.start(); }
From source file:gov.hhs.fha.nhinc.lift.clientController.SocketClientManagerController.java
@Override public final void run() { while (true) { Socket socket = null; InputStream in = null;/*w ww . j a v a 2 s .c o m*/ URI writtenFile = null; String errorMesg = null; LiftMessage mesg = null; try { socket = server.accept(); while (socket == null) { socket = server.accept(); } in = socket.getInputStream(); log.debug("Server " + server.getInetAddress() + " connecting to socket " + socket.getInetAddress() + ": " + socket.getPort()); InterProcessSocketProtocol processSocket = new InterProcessSocketProtocol(); String message = processSocket.readData(in); log.info("SocketClientManagerController received message: " + message); if (message != null) { mesg = (LiftMessage) JaxbUtil.unmarshalFromReader(new StringReader(message), LiftMessage.class); System.out.println("Setting " + mesg.getRequest().getRequest() + " to in progress"); mesgState.add(mesg.getRequest().getRequest()); writtenFile = manager.startClient(mesg, this); } } catch (JAXBException ex) { errorMesg = "Client is unable to process LiftMessage " + ex.getMessage(); log.error(errorMesg); } catch (IOException e) { errorMesg = "Client is unable to process incoming socket information " + e.getMessage(); log.error(errorMesg); } finally { if (socket != null) { try { log.debug("Closing socket " + socket); socket.close(); } catch (IOException ex) { log.warn("Unable to close socket " + socket); } } if (writtenFile != null) { reportSuccess(mesg.getRequest().getRequest(), writtenFile); } else { if (mesg != null && mesg.getRequest() != null && mesg.getRequest().getRequest() != null) { reportFailure(mesg.getRequest().getRequest(), errorMesg); } else { reportFailure(null, errorMesg); } } } } }
From source file:org.apache.hama.util.BSPNetUtils.java
/** * Like {@link NetUtils#connect(Socket, SocketAddress, int)} but also takes a * local address and port to bind the socket to. * /*from w w w . j ava 2s . c o m*/ * @param socket * @param endpoint the remote address * @param localAddr the local address to bind the socket to * @param timeout timeout in milliseconds */ public static void connect(Socket socket, SocketAddress endpoint, SocketAddress localAddr, int timeout) throws IOException { if (socket == null || endpoint == null || timeout < 0) { throw new IllegalArgumentException("Illegal argument for connect()"); } SocketChannel ch = socket.getChannel(); if (localAddr != null) { socket.bind(localAddr); } if (ch == null) { // let the default implementation handle it. socket.connect(endpoint, timeout); } else { SocketIOWithTimeout.connect(ch, endpoint, timeout); } // There is a very rare case allowed by the TCP specification, such that // if we are trying to connect to an endpoint on the local machine, // and we end up choosing an ephemeral port equal to the destination port, // we will actually end up getting connected to ourself (ie any data we // send just comes right back). This is only possible if the target // daemon is down, so we'll treat it like connection refused. if (socket.getLocalPort() == socket.getPort() && socket.getLocalAddress().equals(socket.getInetAddress())) { LOG.info("Detected a loopback TCP socket, disconnecting it"); socket.close(); throw new ConnectException("Localhost targeted connection resulted in a loopback. " + "No daemon is listening on the target port."); } }
From source file:org.apache.hadoop.hdfs.protocol.datatransfer.sasl.SaslDataTransferClient.java
/** * Sends client SASL negotiation for a socket if required. * * @param socket connection socket// ww w . j av a 2s. c o m * @param underlyingOut connection output stream * @param underlyingIn connection input stream * @param encryptionKeyFactory for creation of an encryption key * @param accessToken connection block access token * @param datanodeId ID of destination DataNode * @return new pair of streams, wrapped after SASL negotiation * @throws IOException for any error */ public IOStreamPair socketSend(Socket socket, OutputStream underlyingOut, InputStream underlyingIn, DataEncryptionKeyFactory encryptionKeyFactory, Token<BlockTokenIdentifier> accessToken, DatanodeID datanodeId) throws IOException { IOStreamPair ios = checkTrustAndSend(socket.getInetAddress(), underlyingOut, underlyingIn, encryptionKeyFactory, accessToken, datanodeId); return ios != null ? ios : new IOStreamPair(underlyingIn, underlyingOut); }