Example usage for java.net Socket getPort

List of usage examples for java.net Socket getPort

Introduction

In this page you can find the example usage for java.net Socket getPort.

Prototype

public int getPort() 

Source Link

Document

Returns the remote port number to which this socket is connected.

Usage

From source file:ee.ria.xroad.proxy.clientproxy.FastestConnectionSelectingSSLSocketFactory.java

private SSLSocket wrapToSSLSocket(Socket socket) throws IOException {
    if (socket instanceof SSLSocket) {
        return (SSLSocket) socket;
    }//  w  w  w .j  a va2 s .co  m

    Socket sslSocket = socketfactory.createSocket(socket, socket.getInetAddress().getHostName(),
            socket.getPort(), SystemProperties.isUseSslSocketAutoClose());
    if (sslSocket instanceof SSLSocket) {
        return (SSLSocket) sslSocket;
    }

    throw new CodedException(X_INTERNAL_ERROR, "Failed to create SSL socket");
}

From source file:any.Linker.java

public void serve(final int port) {
    logger.info("+SERVICE: started to serve");

    try {/* w w w  .  j a v  a2s .  co  m*/
        // Start the server socket (?)
        serverSocket = new ServerSocket(port);

        while (true) {
            final Socket socket = serverSocket.accept();
            logger.info(
                    socket.getInetAddress().getCanonicalHostName() + ":" + socket.getPort() + " is connected");

            IConnection conn = new Connection(Thread.currentThread().getName(), this, socket);
            namedCon.put(socket.getInetAddress().getCanonicalHostName() + ":" + socket.getPort(), conn);
            // namedCon.put( "host", conn);
            logger.info("+SERVICE: connected to client " + socket.getInetAddress().getCanonicalHostName() + ":"
                    + socket.getPort());
        }
    } catch (IOException e) {
        logger.error("+SERVICE, serve IO exception", e);
    } catch (InterruptedException e) {
        logger.error("+SERVICE, main loop interupted", e);
    }
}

From source file:com.bittorrent.mpetazzoni.client.ConnectionHandler.java

/**
 * Return a human-readable representation of a connected socket channel.
 *
 * @param channel The socket channel to represent.
 * @return A textual representation (<em>host:port</em>) of the given
 * socket.//from   ww w. ja  v a  2 s .c o m
 */
private String socketRepr(SocketChannel channel) {
    Socket s = channel.socket();
    return String.format("%s:%d%s", s.getInetAddress().getHostName(), s.getPort(),
            channel.isConnected() ? "+" : "-");
}

From source file:com.zimbra.cs.mailclient.MailConnection.java

private SSLSocket newSSLSocket(Socket sock) throws IOException {
    return (SSLSocket) getSSLSocketFactory().createSocket(sock, sock.getInetAddress().getHostName(),
            sock.getPort(), false);
}

From source file:com.ettrema.ldap.LdapConnection.java

/**
 * Initialize the streams and start the thread.
 *
 * @param clientSocket LDAP client socket
 *///from  ww  w.  ja  v  a  2 s.c o  m
public LdapConnection(Socket clientSocket, UserFactory userSessionFactory, List<PropertySource> propertySources,
        SearchManager searchManager, LdapTransactionManager txManager) {
    super(LdapConnection.class.getSimpleName() + '-' + clientSocket.getPort());
    this.searchManager = searchManager;
    this.client = clientSocket;
    this.txManager = txManager;
    setDaemon(true);
    this.userFactory = userSessionFactory;
    this.propertyMapper = new LdapPropertyMapper(new PropFindPropertyBuilder(propertySources));
    try {
        is = new BufferedInputStream(client.getInputStream());
        os = new BufferedOutputStream(client.getOutputStream());
    } catch (IOException e) {
        close();
        throw new RuntimeException(e);
    }
    responseHandler = new LdapResponseHandler(client, os);
    ldapParser = new LdapParser(propertyMapper, responseHandler, userFactory);
    System.out.println("Created LDAP Connection handler");
}

From source file:io.milton.ldap.LdapConnection.java

/**
 * Initialize the streams and start the thread.
 *
 * @param clientSocket LDAP client socket
 *//*from  w ww. j av  a2 s .  c  o  m*/
public LdapConnection(Socket clientSocket, UserFactory userSessionFactory, SearchManager searchManager,
        LdapTransactionManager txManager, PropFindPropertyBuilder propFindPropertyBuilder) {
    super(LdapConnection.class.getSimpleName() + '-' + clientSocket.getPort());
    this.searchManager = searchManager;
    this.client = clientSocket;
    this.txManager = txManager;
    setDaemon(true);
    this.userFactory = userSessionFactory;
    this.propertyMapper = new LdapPropertyMapper(propFindPropertyBuilder);
    try {
        is = new BufferedInputStream(client.getInputStream());
        os = new BufferedOutputStream(client.getOutputStream());
    } catch (IOException e) {
        close();
        throw new RuntimeException(e);
    }
    responseHandler = new LdapResponseHandler(client, os);
    ldapParser = new LdapParser(propertyMapper, responseHandler, userFactory);
    System.out.println("Created LDAP Connection handler");
}

From source file:immf.MyWiser.java

/**
 * Create a new SMTP server with this class as the listener.
 * The default port is 25. Call setPort()/setHostname() before
 * calling start()./*from  ww w.  ja v a 2 s  .  c om*/
 */
public MyWiser(UsernamePasswordValidator userPass, int port, MyWiserMailListener listener,
        final String tlsKeyStore, final String tlsKeyType, final String tlsKeyPasswd) {
    if (tlsKeyStore == null) {
        log.info("SMTP Server disable TLS");
        this.server = new SMTPServer(this, new EasyAuthenticationHandlerFactory(userPass));
        this.server.setHideTLS(true); // TLS?

    } else {
        // TLS
        log.info("SMTP Server enable TLS");
        this.server = new SMTPServer(this, new EasyAuthenticationHandlerFactory(userPass)) {
            public SSLSocket createSSLSocket(Socket socket) throws IOException {
                SSLSocketFactory sf = createSslSocketFactory(tlsKeyStore, tlsKeyType, tlsKeyPasswd);
                InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
                SSLSocket s = (SSLSocket) (sf.createSocket(socket, remoteAddress.getHostName(),
                        socket.getPort(), true));

                s.setUseClientMode(false);

                s.setEnabledCipherSuites(s.getSupportedCipherSuites());

                return s;
            }
        };
        this.server.setRequireTLS(true); // TLS
    }
    this.server.setPort(port);
    this.listener = listener;
}

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  a v  a  2 s .  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:at.tugraz.ist.akm.webservice.server.ServerThread.java

@Override
public void run() {
    mRunning = true;/*w w w .  j  av a 2 s .  co  m*/
    while (mRunning) {
        Socket socket = null;
        try {
            socket = mServerSocket != null ? mServerSocket.accept() : null;
        } catch (IOException ioException) {
            // OK: no need to write trace
        }

        if (mStopServerThread) {
            break;
        }
        if (socket != null) {
            mLog.debug("connection request from ip <" + socket.getInetAddress() + "> on port <"
                    + socket.getPort() + ">");

            final Socket finalSocketReference = socket;
            try {
                mThreadPool.executeTask(new Runnable() {
                    @Override
                    public void run() {
                        DefaultHttpServerConnection serverConn = new DefaultHttpServerConnection();
                        try {
                            HttpParams params = new BasicHttpParams();
                            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
                            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

                            serverConn.bind(finalSocketReference, params);
                            HttpService httpService = initializeHTTPService();
                            httpService.handleRequest(serverConn, mHttpContext);

                            synchronized (ServerThread.this) {
                                HttpConnectionMetrics connMetrics = serverConn.getMetrics();
                                mSentBytesCount += connMetrics.getSentBytesCount();
                                mReceivedBytesCount += connMetrics.getReceivedBytesCount();
                            }
                        } catch (SSLException iDon_tCare) {
                            // some browser send connection closed, some
                            // not ...
                            mLog.info("ignore SSL-connection closed by peer");
                        } catch (ConnectionClosedException iDon_tCare) {
                            mLog.info("ignore connection closed by peer");
                        } catch (Exception ex) {
                            mLog.error("exception caught while processing HTTP client connection", ex);
                        }
                    }
                });
            } catch (RejectedExecutionException reason) {
                mLog.error("request execution rejected because pool works at its limit", reason);
            }
        }
    }

    mRunning = false;
    mLog.info("webserver stopped");
}

From source file:org.springframework.integration.ip.tcp.connection.AbstractTcpConnection.java

public AbstractTcpConnection(Socket socket, boolean server, boolean lookupHost) {
    this.server = server;
    InetAddress inetAddress = socket.getInetAddress();
    if (inetAddress != null) {
        this.hostAddress = inetAddress.getHostAddress();
        if (lookupHost) {
            this.hostName = inetAddress.getHostName();
        } else {/*w  ww. jav  a2s . c  o  m*/
            this.hostName = this.hostAddress;
        }
    }
    int port = socket.getPort();
    this.connectionId = this.hostName + ":" + port + ":" + UUID.randomUUID().toString();
    try {
        this.soLinger = socket.getSoLinger();
    } catch (SocketException e) {
    }
}