Examples of Socket


Examples of java.net.Socket

    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

Examples of java.net.Socket

                } 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

Examples of java.net.Socket

   */
  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

Examples of java.net.Socket

   * @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

Examples of java.net.Socket

   * @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

Examples of java.net.Socket

                        ssoc.setEnabledCipherSuites(ssl.getEnabledCipherSuites());
                    }
                    dataSoc = ssoc;
                } else {
                    LOG.debug("Opening active data connection");
                    dataSoc = new Socket();
                }

                dataSoc.setReuseAddress(true);

                InetAddress localAddr = resolveAddress(dataConfig
                        .getActiveLocalAddress());

                // if no local address has been configured, make sure we use the same as the client connects from
                if(localAddr == null) {
                    localAddr = ((InetSocketAddress)session.getLocalAddress()).getAddress();
                }      

                SocketAddress localSocketAddress = new InetSocketAddress(localAddr, dataConfig.getActiveLocalPort());
               
                LOG.debug("Binding active data connection to {}", localSocketAddress);
                dataSoc.bind(localSocketAddress);

                dataSoc.connect(new InetSocketAddress(address, port));
            } else {

                if (secure) {
                    LOG.debug("Opening secure passive data connection");
                    // this is where we wrap the unsecured socket as a SSLSocket. This is
                    // due to the JVM bug described in FTPSERVER-241.

                    // get server socket factory
                    SslConfiguration ssl = getSslConfiguration();
                   
                    // we've already checked this, but let's do it again
                    if (ssl == null) {
                        throw new FtpException(
                                "Data connection SSL not configured");
                    }

                    SSLSocketFactory ssocketFactory = ssl.getSocketFactory();

                    Socket serverSocket = servSoc.accept();

                    SSLSocket sslSocket = (SSLSocket) ssocketFactory
                            .createSocket(serverSocket, serverSocket
                                    .getInetAddress().getHostAddress(),
                                    serverSocket.getPort(), true);
                    sslSocket.setUseClientMode(false);

                    // initialize server socket
                    if (ssl.getClientAuth() == ClientAuth.NEED) {
                        sslSocket.setNeedClientAuth(true);
View Full Code Here

Examples of java.net.Socket

public class Start {
    public Start(String args[]) {
//      if(args.length == 0)
//        return;

      Socket sck = null;
      PrintWriter pw = null;
      try {         
        System.out.println("StartSocket: passing startup args to already-running Azureus java process.");
       
        sck = new Socket("127.0.0.1", 6880);
       
        pw = new PrintWriter(new OutputStreamWriter(sck.getOutputStream(),"UTF8"));
       
        StringBuffer buffer = new StringBuffer("Azureus Start Server Access;args;");
       
        for(int i = 0 ; i < args.length ; i++) {
          String arg = args[i].replaceAll("&","&&").replaceAll(";","&;");
          buffer.append(arg);
          buffer.append(';');
        }
      
        pw.println(buffer.toString());
        pw.flush();
      } catch(Exception e) {
        Debug.printStackTrace( e );
      } finally {
        try {
          if (pw != null)
            pw.close();
        } catch (Exception e) {
        }
        try {
          if (sck != null)
            sck.close();
        } catch (Exception e) {
        }
      }
    }
View Full Code Here

Examples of java.net.Socket

     */
    private InputStream getDataInputStream() throws IOException {
        try {

            // get data socket
            Socket dataSoc = socket;
            if (dataSoc == null) {
                throw new IOException("Cannot open data connection.");
            }

            // create input stream
            InputStream is = dataSoc.getInputStream();
            if (factory.isZipMode()) {
                is = new InflaterInputStream(is);
            }
            return is;
        } catch (IOException ex) {
View Full Code Here

Examples of java.net.Socket

     */
    private OutputStream getDataOutputStream() throws IOException {
        try {

            // get data socket
            Socket dataSoc = socket;
            if (dataSoc == null) {
                throw new IOException("Cannot open data connection.");
            }

            // create output stream
            OutputStream os = dataSoc.getOutputStream();
            if (factory.isZipMode()) {
                os = new DeflaterOutputStream(os);
            }
            return os;
        } catch (IOException ex) {
View Full Code Here

Examples of java.net.Socket

  public void
  connect()
    throws IOException
   
  {
    socket = new Socket( "127.0.0.1", MagnetURIHandler.getSingleton().getPort());
           
    String  get = "GET " + "/download/" + getURL().toString().substring( 7 ) + " HTTP/1.0" + NL + NL;
   
    socket.getOutputStream().write( get.getBytes());
   
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. 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.