Example usage for java.net InetSocketAddress InetSocketAddress

List of usage examples for java.net InetSocketAddress InetSocketAddress

Introduction

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

Prototype

private InetSocketAddress(int port, String hostname) 

Source Link

Usage

From source file:gridool.util.xfer.TransferServer.java

public void setup(int port) throws IOException {
    ServerSocket servSocket = serverChannel.socket();
    servSocket.setReuseAddress(true);/*from  w ww  .  ja  va 2 s . c  o m*/
    InetAddress addr = NetUtils.getLocalHost(false);
    InetSocketAddress sockaddr = new InetSocketAddress(addr, port);
    servSocket.bind(sockaddr);
}

From source file:net.pms.network.HTTPServer.java

public boolean start() throws IOException {
    hostname = configuration.getServerHostname();
    InetSocketAddress address;/*from  ww  w  .ja v a2s  .  co  m*/

    if (StringUtils.isNotBlank(hostname)) {
        logger.info("Using forced address " + hostname);
        InetAddress tempIA = InetAddress.getByName(hostname);

        if (tempIA != null && networkInterface != null
                && networkInterface.equals(NetworkInterface.getByInetAddress(tempIA))) {
            address = new InetSocketAddress(tempIA, port);
        } else {
            address = new InetSocketAddress(hostname, port);
        }
    } else if (isAddressFromInterfaceFound(configuration.getNetworkInterface())) { // XXX sets iafinal and networkInterface
        logger.info("Using address {} found on network interface: {}", iafinal,
                networkInterface.toString().trim().replace('\n', ' '));
        address = new InetSocketAddress(iafinal, port);
    } else {
        logger.info("Using localhost address");
        address = new InetSocketAddress(port);
    }

    logger.info("Created socket: " + address);

    if (configuration.isHTTPEngineV2()) { // HTTP Engine V2
        group = new DefaultChannelGroup("myServer");
        factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
                Executors.newCachedThreadPool());

        ServerBootstrap bootstrap = new ServerBootstrap(factory);
        HttpServerPipelineFactory pipeline = new HttpServerPipelineFactory(group);
        bootstrap.setPipelineFactory(pipeline);
        bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.setOption("child.keepAlive", true);
        bootstrap.setOption("reuseAddress", true);
        bootstrap.setOption("child.reuseAddress", true);
        bootstrap.setOption("child.sendBufferSize", 65536);
        bootstrap.setOption("child.receiveBufferSize", 65536);
        channel = bootstrap.bind(address);
        group.add(channel);

        if (hostname == null && iafinal != null) {
            hostname = iafinal.getHostAddress();
        } else if (hostname == null) {
            hostname = InetAddress.getLocalHost().getHostAddress();
        }
    } else { // HTTP Engine V1
        serverSocketChannel = ServerSocketChannel.open();

        serverSocket = serverSocketChannel.socket();
        serverSocket.setReuseAddress(true);
        serverSocket.bind(address);

        if (hostname == null && iafinal != null) {
            hostname = iafinal.getHostAddress();
        } else if (hostname == null) {
            hostname = InetAddress.getLocalHost().getHostAddress();
        }

        runnable = new Thread(this, "HTTP Server");
        runnable.setDaemon(false);
        runnable.start();
    }

    return true;
}

From source file:com.chenyang.proxy.http.HttpUserAgentForwardHandler.java

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception {

    final Channel uaChannel = uaChannelCtx.channel();

    final HttpRemote apnProxyRemote = uaChannel.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();

    if (msg instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) msg;

        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());

        if (remoteChannel != null && remoteChannel.isActive()) {
            HttpRequest request = constructRequestForProxy(httpRequest, apnProxyRemote);
            remoteChannel.writeAndFlush(request);
        } else {/*from  w  ww.j ava 2 s  .com*/

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(uaChannel.eventLoop()).channel(NioSocketChannel.class)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .option(ChannelOption.AUTO_READ, false)
                    .handler(new HttpRemoteForwardChannelInitializer(uaChannel, this));

            ChannelFuture remoteConnectFuture = bootstrap.connect(apnProxyRemote.getInetSocketAddress(),
                    new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0));
            remoteChannel = remoteConnectFuture.channel();
            remoteChannelMap.put(apnProxyRemote.getRemoteAddr(), remoteChannel);

            remoteConnectFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        future.channel().write(constructRequestForProxy((HttpRequest) msg, apnProxyRemote));

                        for (HttpContent hc : httpContentBuffer) {
                            future.channel().writeAndFlush(hc);

                            if (hc instanceof LastHttpContent) {
                                future.channel().writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(new ChannelFutureListener() {
                                            @Override
                                            public void operationComplete(ChannelFuture future)
                                                    throws Exception {
                                                if (future.isSuccess()) {
                                                    future.channel().read();
                                                }

                                            }
                                        });
                            }
                        }
                        httpContentBuffer.clear();
                    } else {
                        HttpErrorUtil.writeAndFlush(uaChannel, HttpResponseStatus.INTERNAL_SERVER_ERROR);
                        httpContentBuffer.clear();
                        future.channel().close();
                    }
                }
            });

        }
        ReferenceCountUtil.release(msg);
    } else {
        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());
        HttpContent hc = ((HttpContent) msg);
        if (remoteChannel != null && remoteChannel.isActive()) {
            remoteChannel.writeAndFlush(hc);

            if (hc instanceof LastHttpContent) {
                remoteChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            future.channel().read();
                        }

                    }
                });
            }
        } else {
            httpContentBuffer.add(hc);
        }
    }

}

From source file:com.navercorp.pinpoint.collector.receiver.thrift.udp.UDPReceiverTest.java

@Test
public void hostNullCheck() {
    InetSocketAddress address = new InetSocketAddress((InetAddress) null, PORT);
    logger.debug(address.toString());
}

From source file:info.guardianproject.net.SocksSocketFactory.java

public Socket createSocket(Socket sock, InetAddress localAddress, int localPort, HttpParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {

    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null.");
    }/*from w  w  w.ja v  a 2s.  c  om*/

    if (sock == null)
        sock = createSocket();

    if ((localAddress != null) || (localPort > 0)) {

        // we need to bind explicitly
        if (localPort < 0)
            localPort = 0; // indicates "any"

        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sock.bind(isa);
    }

    return new SocksSocket(sProxy);

}

From source file:be.vlaanderen.sesam.monitor.MonitorTask.java

public void run() {
    if (running.get()) {
        // Do not run (the same instance) concurrent (has state).
        log.warn("Task: " + getName() + " is still running! (skipping)");
        return;/*w w w  .  ja v  a 2 s  .  c o  m*/

    } else {
        running.set(true);
        start = System.currentTimeMillis();
        timewaited = 0;

        try {
            log.debug("Running task: " + getName());

            InetSocketAddress addr = new InetSocketAddress(getRequestHostname(), getRequestPort());
            if (addr.getAddress() == null) {
                logResult(NOTIFICATIONTYPE_EXCEPTION,
                        "Kon ip-adres van host niet vinden, foute hostnaam of niet in DNS? (Host: "
                                + getRequestHostname() + ")");
                running.set(false);

            } else {
                OutboundHandler out = new OutboundHandler();
                ChannelFuture cf = clientService.createClientChannel(out, addr, getResponseTimeoutMillis());
                boolean res = cf.awaitUninterruptibly(getResponseTimeoutMillis());
                if (res) {
                    timewaited = System.currentTimeMillis() - start;
                    if (cf.isSuccess()) {
                        out.sendRequest(cf.getChannel());
                    } // else is handled by exceptioncaught
                } else {
                    logResult(NOTIFICATIONTYPE_TIMEOUT);
                    cf.cancel();
                    running.set(false);
                }
            }
        } catch (Exception e) {
            logResult(NOTIFICATIONTYPE_EXCEPTION, e.getMessage());
            running.set(false);
        }
    }
}

From source file:mina.UnsyncClientSupport.java

/**
 * FTS?/* w ww  .  ja  v a2 s.c  o  m*/
 * 
 * @return
 * @throws CommunicationException
 * @throws InterruptedException
 */
public IoSession connect() throws InterruptedException {
    timer = new Timer();
    if (null != this.session && !session.isConnected()) {
        //??
        return this.session;
    }
    if (connector != null) {
        connector.connect();
        return this.session;
    }
    connector = new NioSocketConnector();
    connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);
    connector.getFilterChain().addLast("threadPool", new ExecutorFilter(Executors.newSingleThreadExecutor()));
    connector.getFilterChain().addLast("logger", new LoggingFilter());
    connector.setHandler(new ClientMsgReceiveHandle());// ???
    try {
        connector.setDefaultRemoteAddress(
                new InetSocketAddress(EPSConstant.UNSYNC_CLIENT_IP, EPSConstant.UNSYNC_CLIENT_PORT));
        ConnectFuture future = connector.connect(new InetSocketAddress(this.hostname, this.port));
        future.awaitUninterruptibly();
        IoSession session = future.getSession();
        this.setSession(session);
        //???????
        timer = new Timer();
        timer.schedule(new HoldConnectionTask(), 0, 60000);
    } catch (RuntimeIoException e) {
        e.printStackTrace();
    }
    return session;
}

From source file:de.quist.samy.remocon.RemoteSession.java

private String initialize() throws UnknownHostException, IOException {
    logger.debug("Creating socket for host " + host + " on port " + port);

    socket = new Socket();
    socket.connect(new InetSocketAddress(host, port), 5000);

    logger.debug("Socket successfully created and connected");
    InetAddress localAddress = socket.getLocalAddress();
    logger.debug("Local address is " + localAddress.getHostAddress());

    logger.debug("Sending registration message");
    writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    writer.append((char) 0x00);
    writeText(writer, APP_STRING);/*from w  ww .  j a va 2 s .com*/
    writeText(writer, getRegistrationPayload(localAddress.getHostAddress()));
    writer.flush();

    InputStream in = socket.getInputStream();
    reader = new InputStreamReader(in);
    String result = readRegistrationReply(reader);
    //sendPart2();
    int i;
    while ((i = in.available()) > 0) {
        in.skip(i);
    }
    return result;
}

From source file:com.googlecode.jmxtrans.model.output.StatsDTelegrafWriterFactory.java

public StatsDTelegrafWriterFactory(@JsonProperty("bucketType") String bucketType,
        @JsonProperty("host") String host, @JsonProperty("port") Integer port,
        @JsonProperty("tags") ImmutableMap<String, String> tags,
        @JsonProperty("resultTags") List<String> resultTags,
        @JsonProperty("flushStrategy") String flushStrategy,
        @JsonProperty("flushDelayInSeconds") Integer flushDelayInSeconds,
        @JsonProperty("poolSize") Integer poolSize) {
    this.bucketTypes = StringUtils.split(firstNonNull(bucketType, "c"), ",");
    this.server = new InetSocketAddress(checkNotNull(host, "Host cannot be null."),
            checkNotNull(port, "Port cannot be null."));
    this.resultAttributesToWriteAsTags = initResultAttributesToWriteAsTags(resultTags);
    this.tags = initCustomTagsMap(tags);
    this.flushStrategy = createFlushStrategy(flushStrategy, flushDelayInSeconds);
    this.poolSize = firstNonNull(poolSize, 1);
}