Example usage for java.net Socket getInetAddress

List of usage examples for java.net Socket getInetAddress

Introduction

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

Prototype

public InetAddress getInetAddress() 

Source Link

Document

Returns the address to which the socket is connected.

Usage

From source file:com.l2jfree.status.StatusServer.java

License:asdf

@Override
public final void run() {
    try {//from   w w  w .  j a  v a 2s. c o m
        main_loop: while (!_socket.isClosed()) {
            try {
                final Socket socket = _socket.accept();
                final String host = socket.getInetAddress().getHostAddress();

                for (Filter filter : _filters) {
                    if (!filter.accept(host)) {
                        _log.warn("Telnet: Connection attempt from " + host + " rejected.");
                        continue main_loop;
                    }
                }

                _log.warn("Telnet: Connection attempt from " + host + " accepted.");

                newStatusThread(socket).start();
            } catch (IOException e) {
                _log.warn("", e);
            }
        }
    } finally {
        close();
    }
}

From source file:httpscheduler.LateBindingRequestListenerThread.java

@Override
public void run() {
    System.out.println("Listening on port " + this.serversocket.getLocalPort());
    ArrayList<String> workerList = new ArrayList<>();

    // Read list of workers from configuration file
    try (BufferedReader br = new BufferedReader(new FileReader("./config/workers.conf"))) {
        for (String line; (line = br.readLine()) != null;) {
            workerList.add(line);//  w  w w  .ja v  a  2s .  com
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(GenericRequestListenerThread.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GenericRequestListenerThread.class.getName()).log(Level.SEVERE, null, ex);
    }

    // Initialize worker manager
    try {
        WorkerManager.useWorkerList(workerList);
    } catch (Exception ex) {
        Logger.getLogger(GenericRequestListenerThread.class.getName()).log(Level.SEVERE, null, ex);
        System.exit(-1);
    }
    WorkerManager.printWorkerMap();

    //jobMap.put(1, new String[1000]);
    Thread workerStatusThread = new UpdateWorkerStatusThread();
    workerStatusThread.start();
    System.out.println("ready for connections");
    while (!Thread.interrupted()) {
        try {
            // Set up HTTP connection
            Socket socket = this.serversocket.accept();
            System.out.println("Incoming connection from " + socket.getInetAddress());
            HttpServerConnection conn = this.connFactory.createConnection(socket);

            // Initialize the pool
            Thread connectionHandler = new ConnectionHandlerThread(this.httpService, conn);

            connectionHandler.setDaemon(false);
            connectionHandlerExecutor.execute(connectionHandler);
            System.out.println("\tConnection Handler Thread created");
        } catch (InterruptedIOException ex) {
            break;
        } catch (IOException e) {
            System.err.println("I/O error initialising connection thread: " + e.getMessage());
            break;
        }
    }
    // when the listener is interupted shutdown the pool
    // and wait for any Connection Handler threads still running
    connectionHandlerExecutor.shutdown();
    while (!connectionHandlerExecutor.isTerminated()) {
    }

    System.out.println("Finished all connection handler threads");
}

From source file:br.com.i9torpedos.model.service.serverSocket.DSSocketSIM2.java

@Override
public void run() {

    try {/* w w  w  .  ja  v  a2  s .co m*/
        while (true) {
            Socket socket = server.accept();
            log.info("Cliente conectado  " + socket.getInetAddress());

            try {

                PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
                printWriter.println(new Date().toString() + "Teste Servidor");
                log.info("Sinal de autenticao enviado para o Cliente  " + new Date().toString());

                //Faz verificao no fluxo de entrada do Objeto
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());

                try {

                    //faz a leitura do Objeto de entrada
                    Object readObject = objectInputStream.readObject();

                    if (readObject instanceof SendSMSMessage) {

                        try {
                            SendSMSMessage smsMessage = (SendSMSMessage) readObject;

                            // Thread.sleep(random.nextInt(10000));

                            ponte.set(smsMessage);
                            new Thread(new ConsumerSendSMSMessage(ponte), "PONTE_ASYNC_DSSOCKETSIM2").start();
                            listaSMS.add(smsMessage);

                            objectInputStream.close();
                            socket.close();

                            if (listaSMS.size() > 0 && !listaSMS.isEmpty()) {

                                DServiceModem2 md2 = new DServiceModem2(listaSMS, 10000);
                                new Thread(md2, "MODEM 2").start();
                                listaSMS.clear();

                            }

                        } catch (InterruptedException ex) {
                            Logger.getLogger(DSSocketSIM2.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }

                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(DSSocketSIM2.class.getName()).log(Level.SEVERE, null, ex);
                }

            } catch (IOException ex) {
                Logger.getLogger(DSSocketSIM2.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    socket.close();
                } catch (IOException ex) {
                    Logger.getLogger(DSSocketSIM2.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(DSSocketSIM2.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            server.close();
        } catch (IOException ex) {
            Logger.getLogger(DSSocketSIM2.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:Server.ConnectionHandler.java

private void initialize(Socket client) {
    this.client = client;
    client_in.addListener(this);
    InetAddress clientAdress = client.getInetAddress();
    hostName = clientAdress.getHostName();
    hostAddress = clientAdress.getHostAddress();

    System.out.println("Client accepted: ");
    System.out.println("Hostname: " + hostName);
    System.out.println("Hostaddress: " + hostAddress);
    System.out.println("Session token: " + my_session_token);
    System.out.println("Nickname : " + my_nickname + " (will be changed in a few milliseconds)");
}

From source file:br.com.i9torpedos.model.service.serverSocket.DSSocketSIM1.java

@Override
public void run() {

    try {/*from  w  ww .  j a v a  2  s  .co m*/
        while (true) {
            Socket socket = server.accept();
            log.info("Cliente conectado  " + socket.getInetAddress());

            try {

                PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
                printWriter.println(conectou);
                log.info("Sinal de autenticao enviado para o Cliente  " + new Date().toString());

                //Faz verificao no fluxo de entrada do Objeto
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());

                try {

                    //faz a leitura do Objeto de entrada
                    Object readObject = objectInputStream.readObject();

                    if (readObject instanceof SendSMSMessage) {

                        try {

                            SendSMSMessage smsMessage = (SendSMSMessage) readObject;

                            // Thread.sleep(random.nextInt(10000));

                            ponte.set(smsMessage);
                            Thread t = new Thread(new ConsumerSendSMSMessage(ponte),
                                    "PONTE_ASYNC_DSSOCKETSIM1");
                            t.start();

                            listaSMS.add(smsMessage);

                            objectInputStream.close();
                            socket.close();

                            if (listaSMS.size() > 0 && !listaSMS.isEmpty()) {

                                DServiceModem1 md1 = new DServiceModem1(listaSMS, 1000);
                                new Thread(md1, "MODEM 1").start();
                                listaSMS.clear();

                            }

                        } catch (InterruptedException ex) {
                            Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }

                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
                }

            } catch (IOException ex) {
                Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    socket.close();
                } catch (IOException ex) {
                    Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            server.close();
        } catch (IOException ex) {
            Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:pluginmanager.RequestManager.java

public void process(HttpRequest request, Server server, Socket socket, long start) {
    boolean throttled = false;
    if (throttleMap.containsKey(socket.getInetAddress().toString())) {
        long last = throttleMap.get(socket.getInetAddress().toString());
        long diff = start - last;
        if (diff < throttleRate) {
            server.incrementConnections(1);
            long end = System.currentTimeMillis();
            server.incrementServiceTime(end - start);
            System.out.println("THROTTLED " + diff);
            throttled = true;//w  w  w.  jav  a  2  s  .c  o m
        }
    }
    throttleMap.put(socket.getInetAddress().getHostAddress(), start);

    System.out.println("Adding to queue");
    if (throttled) {
        System.out.println("Throttled request added");
    }
    System.out.println(server.getPort());
    queue.add(new PriorityRequest(request, server.getRootDirectory(), currentRequestId, start, throttled));
    sockDrawer.put(currentRequestId, socket);
    currentRequestId++;
    System.out.println("Queue is this large " + queue.size());
}

From source file:com.l2jfree.loginserver.thread.FloodProtectedListener.java

private boolean isFlooding(Socket connection) {
    if (!Config.FLOOD_PROTECTION)
        return false;

    final String host = connection.getInetAddress().getHostAddress();

    ForeignConnection fConnection = _floodProtection.get(host);
    if (fConnection != null) {
        fConnection.connectionNumber += 1;

        if ((fConnection.connectionNumber > Config.FAST_CONNECTION_LIMIT
                && (System.currentTimeMillis() - fConnection.lastConnection) < Config.NORMAL_CONNECTION_TIME)
                || (System.currentTimeMillis() - fConnection.lastConnection) < Config.FAST_CONNECTION_TIME
                || fConnection.connectionNumber > Config.MAX_CONNECTION_PER_IP) {
            fConnection.connectionNumber -= 1;
            fConnection.lastConnection = System.currentTimeMillis();

            try {
                connection.close();// w ww. ja  v a 2  s. co m
            } catch (IOException e) {
                _log.warn("", e);
            }

            if (!fConnection.isFlooding)
                _log.info("Potential Flood from " + host);

            fConnection.isFlooding = true;
            return true;
        } else if (fConnection.isFlooding) //if connection was flooding server but now passed the check
        {
            fConnection.isFlooding = false;

            _log.info(host + " is not considered as flooding anymore.");
        }

        fConnection.lastConnection = System.currentTimeMillis();
    } else {
        _floodProtection.put(host, new ForeignConnection());
    }

    return false;
}

From source file:de.th.wildau.dsc.sne.webserver.WebServer.java

/**
 * Web server / main constructor./* ww w  .j  a  v a2s .  c  o  m*/
 * 
 * @param startArguments
 */
public WebServer(String[] startArguments) {

    loadConfiguration(startArguments);
    Log.debug(Configuration.getInstance().toString());

    Log.debug("Information about the OS: " + System.getProperty("os.name") + " - "
            + System.getProperty("os.version") + " - " + System.getProperty("os.arch"));

    if (Configuration.getConfig().getProxyHost() != null) {
        Log.debug("setup proxy configuration");
        System.setProperty("http.proxyHost", Configuration.getConfig().getProxyHost());
        System.setProperty("http.proxyPort", String.valueOf(Configuration.getConfig().getProxyPort()));
    }

    Log.debug("find supported scripting languages");
    supportedScriptLanguages = Collections.unmodifiableList(ScriptExecutor.getSupportedScriptLanguages());
    Log.debug("Supported Script Languages " + Arrays.toString(supportedScriptLanguages.toArray()));

    Log.info("instantiating web server");
    try {
        ServerSocket server = new ServerSocket(Configuration.getConfig().getServerPort());
        Log.debug("bound port " + Configuration.getConfig().getServerPort());

        int corePoolSize = Runtime.getRuntime().availableProcessors();
        int maxPoolSize = (2 * corePoolSize) + 1;
        Log.debug("core/max pool size: " + corePoolSize + "/" + maxPoolSize);
        LinkedBlockingQueue<Runnable> workerQueue = new LinkedBlockingQueue<Runnable>();
        long keepAliveTime = 30;
        /*
         * keepAliveTime - If the pool currently has more than corePoolSize
         * threads, excess threads will be terminated if they have been idle
         * for more than the keepAliveTime.
         */

        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime,
                TimeUnit.SECONDS, workerQueue);
        threadPool.prestartAllCoreThreads();

        Socket socket = null;
        while (true) {

            try {
                socket = server.accept();
                Log.info(socket.getInetAddress().getHostName() + " client request");
                threadPool.execute(new HttpHandler(socket));
                Log.debug("current threads: " + threadPool.getActiveCount());
            } catch (final IOException ex) {
                Log.error("Connection failed!", ex);
            } catch (final RejectedExecutionException ex) {
                // XXX [sne] RejectedExecutionException
                // http://stackoverflow.com/questions/1519725/why-does-executors-newcachedthreadpool-throw-java-util-concurrent-rejectedexecut
                // http://www.javamex.com/tutorials/threads/thread_pools_queues.shtml
                // http://stackoverflow.com/questions/2001086/how-to-make-threadpoolexecutors-submit-method-block-if-it-is-saturated
                Log.error("RejectedExecutionException", ex);
                socket.close();
            } catch (final Exception ex) {
                Log.fatal("Unknown error!", ex);
            }
        }
    } catch (final IOException ex) {
        Log.fatal("Can not start the server!", ex);
        System.err.println("Can not start the server! " + ex.getMessage());
    } catch (final Exception ex) {
        Log.fatal("Unknown error!", ex);
    }
}

From source file:org.squidy.manager.commander.ControlServer.java

@Override
public void run() {
    try {/*from   w ww.ja va2s . c o  m*/
        incomings = new ArrayList<Incoming>();
        outgoings = new ArrayList<Outgoing>();

        while (running) {
            Socket client = server.accept();
            client.setTcpNoDelay(true);

            if (LOG.isInfoEnabled()) {
                LOG.info("Client connected: " + client.getInetAddress() + " on port " + client.getPort());
            }

            clients.add(client);

            Incoming incoming = new Incoming(client.getInputStream(), context);
            Outgoing outgoing = new Outgoing(client.getOutputStream(), context);

            ConnectionPeer connectionPeer = new ConnectionPeer(incoming, outgoing);

            incomings.add(incoming);
            outgoings.add(outgoing);
        }

        for (Incoming incoming : incomings) {
            incoming.close();
        }

        for (Outgoing outgoing : outgoings) {
            outgoing.close();
        }

        for (Socket client : clients) {
            client.close();
        }
    } catch (IOException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Error occured in control server: " + e.getMessage(), e);
        }
    }
}

From source file:org.mitre.honeyclient.OOoConversionServer.java

public void run() {

    boolean shutdown = false;

    while (!shutdown) {
        try {/*from w  ww  .j  a va 2 s. com*/
            Socket socket = serverSocket.accept();

            if ((socket.getInetAddress().getHostName()).equals("localhost.localdomain")) {
                WorkerThread workerThread = new WorkerThread(socket, this);
                workerThread.start();
            } else {

                try {
                    OutputStream out = socket.getOutputStream();
                    mapper.writeValue(out, new Response("Remote connections not allowed.", null, null));
                } catch (IOException e) {
                    //swallow
                }

            }
        } catch (IOException e) {
            Logger.getLogger(WorkerThread.class.getName()).log(Level.SEVERE, null, e);
        }
    }
}