Example usage for java.net Socket toString

List of usage examples for java.net Socket toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Converts this socket to a String .

Usage

From source file:Main.java

License:asdf

public static void main(String args[]) throws Exception {
    Socket s = new Socket("internic.net", 43);
    InputStream in = s.getInputStream();
    OutputStream out = s.getOutputStream();
    String str = "asdfasdfasdf\n";
    byte buf[] = str.getBytes();
    out.write(buf);/*from  w ww. j a v a  2  s .co  m*/
    int c;
    while ((c = in.read()) != -1) {
        System.out.print((char) c);
    }

    System.out.println(s.toString());

    s.close();
}

From source file:com.linkedin.databus2.test.TestUtil.java

/**
 * Checks if a server is running on a given host and port
 * @param host        the server host//from  w w w. j  a v a  2 s  . c  o  m
 * @param port        the server port
 * @param log         logger for diagnostic messages (can be null)
 * @return true if successful
 * @throws IOException
 */
public static boolean checkServerRunning(String host, int port, Logger log, boolean logError) {
    boolean success = false;

    try {
        Socket socket = new Socket(host, port);
        log.info("host=" + host + " port=" + port);
        log.info("Socket Info:" + socket.toString());
        log.info("IsConnected=" + socket.isConnected() + " isClosed=" + socket.isClosed() + " isBound="
                + socket.isBound());
        success = socket.isConnected();
        socket.close();
    } catch (ConnectException ce) {
        if (null != log)
            log.error("Fail to connect to port:" + port);
        if (logError && null != log)
            log.error("Connect error", ce);
        success = false;
    } catch (IOException e) {
        if (logError && null != log)
            log.error("connect error", e);
    } catch (RuntimeException e) {
        if (logError && null != log)
            log.error("runtime error", e);
    }

    return success;
}

From source file:org.wso2.carbon.inbound.iso8583.listening.ISO8583MessageConnection.java

/**
 * create the server socket which is to accept a connection from a client.
 *//*  ww  w.  j  a v  a  2  s  .  c  o  m*/
public void run() {
    try {
        server = new ServerSocket(port);
        log.info("Server is listening on port :" + port);
        while (!listening) {
            try {
                Socket socketConnection = server.accept();
                if (log.isDebugEnabled()) {
                    log.debug("Client connected to socket: " + socketConnection.toString());
                }
                handleClientRequest(socketConnection, params);
            } catch (IOException e1) {
                log.warn("Exception occurred while accept the connections", e1);
            }
        }
    } catch (IOException e) {
        handleException("Server could not listen on port " + port, e);
    } finally {
        try {
            server.close();
        } catch (IOException e) {
            log.error("Error while closing the serverSocket", e);
        }
    }
}

From source file:com.tasktop.c2c.server.web.proxy.ajp.AjpPoolableConnectionFactory.java

@Override
public Object makeObject(Object objectKey) throws Exception {
    Key key = (Key) objectKey;
    String host = key.getHost();/*  w ww  .  j a v  a 2s  .c  om*/
    int port = key.getPort();
    if (port <= 0) {
        port = 8009;
    }

    Socket socket = socketFactory.createSocket(host, port);
    try {
        socket.setTcpNoDelay(tcpNoDelay);
        socket.setSoTimeout(soTimeout);
        socket.setKeepAlive(keepAlive);
    } catch (SocketException e) {
        socket.close();
        throw e;
    }
    debug("Created new socket: " + socket.toString());
    return socket;
}

From source file:net.wimpi.telnetd.net.ConnectionManager.java

/**
 * Method that that tries to connect an incoming request.
 * Properly  queueing.//from   w  ww  .j  a v a  2s.  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.socsimnet.server.Server.java

@Override
public void run() {
    try {/*from  w ww.j a  v a 2  s .  co  m*/
        serverSocket = new ServerSocket(this.port);
        Socket client;
        System.out.println("Server is listening port " + this.port + "...");
        while (!this.stop) {
            try {
                client = serverSocket.accept();
            } catch (SocketException e) {
                break;
            }
            System.out.println("Client accepted " + client.toString() + " hash:" + client.hashCode());
            this.cDB.put(client.hashCode(), client);
            new ClientHandler(this, client).start();
        }
        System.out.println("Server shutting down...");
        printCloseMessage();
        serverSocket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.eclipse.ecf.provider.filetransfer.httpclient.HttpClientRetrieveFileTransfer.java

public synchronized void cancel() {
    Trace.entering(Activator.PLUGIN_ID, DebugOptions.METHODS_ENTERING, this.getClass(), "cancel"); //$NON-NLS-1$
    if (isCanceled()) {
        return; // break job cancel recursion
    }//from   w  w w .j  a v a  2 s . c o  m
    setDoneCanceled(exception);
    boolean fireDoneEvent = true;
    if (connectJob != null) {
        Trace.trace(Activator.PLUGIN_ID, "calling connectJob.cancel()"); //$NON-NLS-1$
        connectJob.cancel();
    }
    synchronized (jobLock) {
        if (job != null) {
            // Its the transfer jobs responsibility to throw the event.
            fireDoneEvent = false;
            Trace.trace(Activator.PLUGIN_ID, "calling transfer job.cancel()"); //$NON-NLS-1$
            job.cancel();
        }
    }
    if (getMethod != null) {
        if (!getMethod.isAborted()) {
            Trace.trace(Activator.PLUGIN_ID, "calling getMethod.abort()"); //$NON-NLS-1$
            getMethod.abort();
        }
    }
    if (connectingSockets != null) {
        // this should unblock socket connect calls, if any
        for (Iterator iterator = connectingSockets.getConnectingSockets().iterator(); iterator.hasNext();) {
            Socket socket = (Socket) iterator.next();
            try {
                Trace.trace(Activator.PLUGIN_ID, "Call socket.close() for socket=" + socket.toString()); //$NON-NLS-1$
                socket.close();
            } catch (IOException e) {
                Trace.catching(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_CATCHING, this.getClass(), "cancel", //$NON-NLS-1$
                        e);
            }
        }
    }
    hardClose();
    if (fireDoneEvent) {
        fireTransferReceiveDoneEvent();
    }
    Trace.exiting(Activator.PLUGIN_ID, DebugOptions.METHODS_EXITING, this.getClass(), "cancel");//$NON-NLS-1$

}

From source file:org.eclipse.jubula.communication.Communicator.java

/**
 * Initializes the given connection and socket, adding necessary listeners
 * and starting to read the input stream of the socket.
 * //from  ww w  .j  av a2 s  .  com
 * @param conn The connection to initialize.
 * @param socket The socket associated with the connection.
 */
private void setup(Connection conn, Socket socket) {
    // add listener
    conn.addMessageHandler(m_connectionListener);
    conn.addErrorHandler(m_errorListener);
    // set an exceptionHandler
    conn.setExceptionHandler(getExceptionHandler());
    // start reading from connection
    String id = socket.toString();
    conn.startReading(id);
    fireConnectionGained(socket.getInetAddress(), socket.getPort());
}

From source file:com.mirth.connect.server.controllers.DefaultMessageObjectController.java

public void updateMessage(MessageObject incomingMessageObject, boolean checkIfMessageExists) {
    MessageObject messageObject = (MessageObject) incomingMessageObject.clone();
    Socket socket = null;

    try {/*  ww  w  .  j  a  va2 s.  c  om*/
        // Check if we have a socket. We need to replace with a string
        // because
        // Sockets are not serializable and we want to retain the socket
        if (messageObject.getChannelMap().containsKey(RECEIVE_SOCKET)) {
            Object socketObj = messageObject.getChannelMap().get(RECEIVE_SOCKET);

            // XXX: Aren't these two cases doing the exact same thing??
            if (socketObj instanceof Socket) {
                socket = (Socket) socketObj;
                messageObject.getChannelMap().put(RECEIVE_SOCKET, socket.toString());
            } else {
                messageObject.getChannelMap().put(RECEIVE_SOCKET, socketObj.toString());
            }

        }
    } catch (Exception e) {
        logger.error(e);
    }

    // update the stats counts
    if (messageObject.getStatus().equals(MessageObject.Status.TRANSFORMED)) {
        statisticsController.incrementReceivedCount(messageObject.getChannelId());
    } else if (messageObject.getStatus().equals(MessageObject.Status.FILTERED)) {
        statisticsController.incrementFilteredCount(messageObject.getChannelId());
    } else if (messageObject.getStatus().equals(MessageObject.Status.ERROR)) {
        statisticsController.incrementErrorCount(messageObject.getChannelId());
    } else if (messageObject.getStatus().equals(MessageObject.Status.SENT)) {
        statisticsController.incrementSentCount(messageObject.getChannelId());
    } else if (messageObject.getStatus().equals(MessageObject.Status.QUEUED)) {
        statisticsController.incrementQueuedCount(messageObject.getChannelId());
    }

    Channel channel = ControllerFactory.getFactory().createChannelController()
            .getDeployedChannelById(messageObject.getChannelId());

    if (channel != null && channel.getProperties().containsKey("store_messages")) {
        // If replacing messages that were stored on special conditions
        // ("store errored only" or "do not store filtered messages"),
        // then try to remove the old message if the new one succeeded.
        if (checkIfMessageExists) {
            if (channel.getProperties().get("store_messages").equals("true")
                    && channel.getProperties().get("error_messages_only").equals("true")
                    && !messageObject.getStatus().equals(MessageObject.Status.ERROR)) {
                try {
                    /*
                     * MIRTH-2098: Don't remove the message from the actual
                     * queue if the new status is QUEUED. Still remove it
                     * from the database so that a queued message doesn't
                     * show up in the message browser when only storing
                     * errored messages.
                     */
                    if (!messageObject.getStatus().equals(MessageObject.Status.QUEUED)) {
                        removeMessageFromQueue(messageObject);
                    }
                    removeMessage(messageObject);
                } catch (Exception e) {
                    logger.error("Could not remove old message: id=" + messageObject.getId(), e);
                }
            }

            if (channel.getProperties().get("store_messages").equals("true")
                    && channel.getProperties().get("dont_store_filtered").equals("true")
                    && messageObject.getStatus().equals(MessageObject.Status.FILTERED)) {
                try {
                    removeMessageFromQueue(messageObject);
                    removeMessage(messageObject);
                } catch (Exception e) {
                    logger.error("Could not remove old message: id=" + messageObject.getId(), e);
                }
            }
        }

        if (channel.getProperties().get("store_messages").equals("false")
                || (channel.getProperties().get("store_messages").equals("true")
                        && channel.getProperties().get("error_messages_only").equals("true")
                        && !messageObject.getStatus().equals(MessageObject.Status.ERROR))
                || (channel.getProperties().get("store_messages").equals("true")
                        && channel.getProperties().get("dont_store_filtered").equals("true")
                        && messageObject.getStatus().equals(MessageObject.Status.FILTERED))) {
            logger.debug("message is not stored");
            return;
        } else if (channel.getProperties().getProperty("encryptData").equals("true")) {
            encryptMessageData(messageObject);
        }
    }

    writeMessageToDatabase(messageObject, checkIfMessageExists);

    if (socket != null) {
        messageObject.getChannelMap().put(RECEIVE_SOCKET, socket);
    }
}