Package java.net

Examples of java.net.Socket


                 "ReliableSSLTcpClient[" + identity + ',' + key + "].createSocket(" +
                 hostname + "," + port + ") on interface " + outLocalAddrStr + ":" + outLocalPort);

    SocketFactory socketFactory = createSocketFactory();
    // AF: Be careful SSLSocketFactory don't allow to use ConnectTimeout
    Socket socket =  socketFactory.createSocket(hostname, port, outLocalAddr, outLocalPort);

    return socket;
  }
View Full Code Here


    /**
     *
     */
    public void run() {
      /** Connected socket. */
      Socket sock = null;

      try {
        // After a stop we needs to create anew the listen socket.
        if (listen == null) {
          // creates a server socket listening on configured port
          listen = createServerSocket();
        }

        while (running) {
          try {
            canStop = true;

            // Get the connection
            try {
              if (this.logmon.isLoggable(BasicLevel.DEBUG))
                this.logmon.log(BasicLevel.DEBUG,
                                this.getName() + ", waiting connection");

              sock = listen.accept();
            } catch (IOException exc) {
              if (running)
                this.logmon.log(BasicLevel.ERROR,
                                this.getName() + ", error during waiting connection", exc);
              continue;
            }
            canStop = false;

            setSocketOption(sock);

            Boot boot = readBoot(sock.getInputStream());
            if (this.logmon.isLoggable(BasicLevel.DEBUG))
              this.logmon.log(BasicLevel.DEBUG,
                              this.getName() + ", connection setup from #" + boot.sid);
            getSession(boot.sid).start(sock, boot.boot);
          } catch (Exception exc) {
            this.logmon.log(BasicLevel.ERROR,
                            this.getName() + ", bad connection setup", exc);
            // Close the incoming connection
            sock.close();
          }
        }
      } catch (IOException exc) {
        this.logmon.log(BasicLevel.ERROR,
                        this.getName() + ", bad socket initialization", exc);
View Full Code Here

        // Set the local attribute in order to block all others local attempts.
        this.local = true;
      }

      Socket sock = null;
      try {
        sock = createSocket(server);
        setSocketOption(sock);

        writeBoot(sock.getOutputStream());
        int boot = readAck(sock.getInputStream());

        AgentServer.getTransaction().begin();
        testBootTS(sid, boot);
        AgentServer.getTransaction().commit(true);

        nis = new NetworkInputStream(sock.getInputStream());
        nos = new NetworkOutputStream(sock.getOutputStream());

        if (logmon.isLoggable(BasicLevel.DEBUG))
          logmon.log(BasicLevel.DEBUG, getName() + ", connection done");

      } catch (Exception exc) {
        if (logmon.isLoggable(BasicLevel.DEBUG))
          logmon.log(BasicLevel.DEBUG, getName() + ", connection aborted", exc);
       
        // Try it later, may be a a connection is in progress...
        try {
          sock.getOutputStream().close();
        } catch (Exception exc2) {}
        try {
          sock.getInputStream().close();
        } catch (Exception exc2) {}
        try {
          sock.close();
        } catch (Exception exc2) {}

        // Reset the local attribute to allow future attempts.
        this.local = false;
View Full Code Here

    synchronized void close() {
      if (logmon.isLoggable(BasicLevel.DEBUG))
        logmon.log(BasicLevel.DEBUG, getName() + ", closed.");

      Socket sock = this.sock;
      this.sock = null;

      sender.stop();

      try {
        sock.getInputStream().close();
      } catch (Exception exc) {}
      try {
        sock.getOutputStream().close();
      } catch (Exception exc) {}
      try {
        sock.close();
      } catch (Exception exc) {}
      // The sock attribute is set to null in the finally clause of NetSession.run(),
      // so it avoids start of session before the thread ending.
      nis = null;
      nos = null;
View Full Code Here

                        server.getServerId() +
                        ", addr=" + sa.getHostname() +
                        ", port=" + sa.getPort());
                 
      try {
        Socket socket = createSocket(sa);

        if (this.logmon.isLoggable(BasicLevel.DEBUG))
          this.logmon.log(BasicLevel.DEBUG, this.getName() + ", connected");

        // Memorize the right address for next try.
View Full Code Here

    public static Socket createSocket(InetAddress host, int port, int timeout)
            throws IOException {

        // don't bother going thru the below if a timeout isn't asked for ...
        if (timeout == 0 || !timeoutSupported) {
            return new Socket(host, port);
        }
        else {
            // attempt to set up 1.4 and later's Socket.connect method which
            // provides a timeout
            try {
                // get the correct connect method
                Class socketAddress = Class.forName("java.net.SocketAddress");
                Method connectMethod = Socket.class.getMethod("connect", new Class[] {
                        socketAddress, int.class });
               
                // create an unconnected socket instance
                Socket sock = (Socket) Socket.class.newInstance();

                // need an InetSocketAddress instance for connect()
                Class inetSocketAddress = Class.forName("java.net.InetSocketAddress");
                Constructor inetSocketAddressCtr =
                    inetSocketAddress.getConstructor(
                            new Class[] { InetAddress.class, int.class });
                Object address = inetSocketAddressCtr.newInstance(
                        new Object[] { host, new Integer(port) });

                // now invoke the connect method with the timeout
                log.debug("Invoking connect with timeout=" + timeout);
                connectMethod.invoke(sock, new Object[]{address, new Integer(timeout)});
                log.debug("Connected successfully");
                return sock;
            }
            catch (InvocationTargetException ex) {
                Throwable target = ex.getTargetException();
                if (target instanceof IOException)
                    throw (IOException)target;
                log.debug("Could not use timeout connecting to host (" + ex.toString() + ")");
                timeoutSupported = false;
                return new Socket(host, port);
            }
            catch (Exception ex) {
                log.debug("Could not use timeout connecting to host (" + ex.toString() + ")");
                timeoutSupported = false;
                return new Socket(host, port);
            }
        }
    }
View Full Code Here

                } else {
                    port = endpoint;
                }
                try {
                    int portnum = Integer.parseInt(port);
                    m_socket = new Socket(host, portnum);
                    m_socket.setTcpNoDelay(true);
                } catch (NumberFormatException e) {
                    throw new WsConfigurationException("Error parsing port number for endpoint '" + endpoint + '\'', e);
                } catch (IOException e) {
                    throw new WsConfigurationException("Unable to create socket connection to endpoint '" + endpoint
View Full Code Here

   */
  private void acceptConnection() throws Exception {
    if (logger.isLoggable(BasicLevel.DEBUG))
      logger.log(BasicLevel.DEBUG, "TcpConnectionListener.acceptConnection()");

    Socket sock = proxyService.getServerSocket().accept();
    String inaddr = sock.getInetAddress().getHostAddress();

    connectionCount++;

    if (logger.isLoggable(BasicLevel.DEBUG))
      logger.log(BasicLevel.DEBUG, " -> accept connection from " + inaddr);

    try {
      sock.setTcpNoDelay(true);

      // Fix bug when the client doesn't use the right protocol (e.g. Telnet)
      // and blocks this listener.
      sock.setSoTimeout(timeout);

      InputStream is = sock.getInputStream();
      NetOutputStream nos = new NetOutputStream(sock);

      byte[] magic = StreamUtil.readByteArrayFrom(is, 8);
      for (int i = 0; i < 5; i++) {
        if (magic.length == i || magic[i] != MetaData.joramMagic[i] && magic[i] > 0) {
          String errorMsg = "Bad magic number. Client is not compatible with JORAM.";
          logger.log(BasicLevel.ERROR, errorMsg);
          protocolErrorCount++;
          throw new IllegalAccessException(errorMsg);
        }
      }
      if (magic[7] != MetaData.joramMagic[7]) {
        if (magic[7] > 0 && MetaData.joramMagic[7] > 0) {
          String errorMsg = "Bad protocol version number " + magic[7] + " != " + MetaData.joramMagic[7];
          logger.log(BasicLevel.ERROR, errorMsg);
          protocolErrorCount++;
          throw new IllegalAccessException(errorMsg);
        }
       
        logger.log(BasicLevel.WARN,
                   "Wildcard protocol version number: from stream = " + magic[7] + ", from MetaData = " + MetaData.joramMagic[7]);
      }

      long dt = Math.abs(StreamUtil.readLongFrom(is) - System.currentTimeMillis());
      if (dt > clockSynchroThreshold)
        logger.log(BasicLevel.WARN, " -> bad clock synchronization between client and server: " + dt);
      StreamUtil.writeTo(dt, nos);

      Identity identity = Identity.read(is);
      if (logger.isLoggable(BasicLevel.DEBUG))
        logger.log(BasicLevel.DEBUG, " -> read identity = " + identity);

      int key = StreamUtil.readIntFrom(is);
      if (logger.isLoggable(BasicLevel.DEBUG))
        logger.log(BasicLevel.DEBUG, " -> read key = " + key);

      int heartBeat = 0;
      if (key == -1) {
        heartBeat = StreamUtil.readIntFrom(is);
        if (logger.isLoggable(BasicLevel.DEBUG))
          logger.log(BasicLevel.DEBUG, " -> read heartBeat = " + heartBeat);
      }

      GetProxyIdNot gpin = new GetProxyIdNot(identity, inaddr);
      AgentId proxyId;
      try {
        gpin.invoke(AdminTopic.getDefault());
        proxyId = gpin.getProxyId();
      } catch (Exception exc) {
        if (logger.isLoggable(BasicLevel.DEBUG))
          logger.log(BasicLevel.DEBUG, "", exc);
        failedLoginCount++;
        StreamUtil.writeTo(1, nos);
        StreamUtil.writeTo(exc.getMessage(), nos);
        nos.send();
        return;
      }

      IOControl ioctrl;
      ReliableConnectionContext ctx;
      if (key == -1) {
        OpenConnectionNot ocn = new OpenConnectionNot(true, heartBeat);
        ocn.invoke(proxyId);
        StreamUtil.writeTo(0, nos);
        ctx = (ReliableConnectionContext) ocn.getConnectionContext();
        key = ctx.getKey();
        StreamUtil.writeTo(key, nos);
        nos.send();
        ioctrl = new IOControl(sock);
      } else {
        GetConnectionNot gcn = new GetConnectionNot(key);
        try {
          gcn.invoke(proxyId);
        } catch (Exception exc) {
          if (logger.isLoggable(BasicLevel.DEBUG))
            logger.log(BasicLevel.DEBUG, "", exc);
          StreamUtil.writeTo(1, nos);
          StreamUtil.writeTo(exc.getMessage(), nos);
          nos.send();
          return;
        }
        ctx = (ReliableConnectionContext) gcn.getConnectionContext();
        StreamUtil.writeTo(0, nos);
        nos.send();
        ioctrl = new IOControl(sock, ctx.getInputCounter());

        TcpConnection tcpConnection = proxyService.getConnection(proxyId, key);
        if (tcpConnection != null) {
          tcpConnection.close();
        }
      }

      // Reset the timeout in order to enable the server to indefinitely
      // wait for requests.
      sock.setSoTimeout(0);

      TcpConnection tcpConnection = new TcpConnection(ioctrl, ctx, proxyId, proxyService, identity);
      tcpConnection.start();
    } catch (IllegalAccessException exc) {
      if (logger.isLoggable(BasicLevel.ERROR))
        logger.log(BasicLevel.ERROR, "", exc);
      sock.close();
      throw exc;
    } catch (IOException exc) {
      if (logger.isLoggable(BasicLevel.DEBUG))
        logger.log(BasicLevel.DEBUG, "", exc);
      sock.close();
      throw exc;
    }
  }
View Full Code Here

   * @param port  the port number.
   * @param timeout  the timeout value to be used in milliseconds.
   */
  public Socket createSocket(InetAddress addr, int port,
                             int timeout) throws IOException {
    Socket socket = new Socket();
    InetSocketAddress endpoint = new InetSocketAddress(addr, port);
    socket.connect(endpoint, timeout);

    return socket;
  }
View Full Code Here

   * @param timeout  the timeout value to be used in milliseconds.
   */
  public Socket createSocket(InetAddress addr, int port,
                             InetAddress localAddr, int localPort,
                             int timeout) throws IOException {
    Socket socket = new Socket();
    InetSocketAddress endpoint = new InetSocketAddress(addr, port);
    InetSocketAddress bindpoint = new InetSocketAddress(localAddr, localPort);
    socket.bind(bindpoint);
    socket.connect(endpoint, timeout);

    return socket;
  }
View Full Code Here

TOP

Related Classes of java.net.Socket

Copyright © 2015 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.