Example usage for java.net ServerSocket accept

List of usage examples for java.net ServerSocket accept

Introduction

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

Prototype

public Socket accept() throws IOException 

Source Link

Document

Listens for a connection to be made to this socket and accepts it.

Usage

From source file:srvserver.thServerSocket.java

@Override
public void run() {
    try {/*  w  ww .  jav a2 s .c o  m*/
        logger.info("Starting Listener Thread Service Server port: " + gDatos.getServiceInfo().getSrvPort());
        String inputData;
        String outputData;
        String dRequest;
        String dAuth;
        JSONObject jHeader;
        JSONObject jData;

        ServerSocket skServidor = new ServerSocket(gDatos.getServiceInfo().getSrvPort());

        while (isSocketActive) {
            Socket skCliente = skServidor.accept();
            InputStream inpStr = skCliente.getInputStream();
            DataInputStream dataInput = new DataInputStream(inpStr);

            //Recibe Data Input (request)
            //
            //Espera Entrada
            //
            try {
                inputData = dataInput.readUTF();
                //gSub.sysOutln(inputData);

                logger.info("Recibiendo TX: " + inputData);
                jHeader = new JSONObject(inputData);
                jData = jHeader.getJSONObject("data");

                dAuth = jHeader.getString("auth");
                dRequest = jHeader.getString("request");

                if (dAuth.equals(gDatos.getServiceInfo().getAuthKey())) {

                    switch (dRequest) {
                    case "getStatus":
                        outputData = gSub.sendDataKeep("request");
                        break;
                    case "getDate":
                        outputData = gSub.sendDate();
                        break;
                    case "updateAssignedProc":
                        gSub.updateAssignedProcess(jData);
                        outputData = gSub.sendOkTX();
                        break;
                    case "executeProcess":
                        logger.info("Ejecutando ...enqueProcess..: " + inputData);
                        int result = gSub.enqueProcess(jData);
                        if (result == 0) {
                            outputData = gSub.sendOkTX();
                        } else {
                            if (result == 2) {
                                outputData = gSub.sendError(99, "Proceso ya se encuntra encolado...");
                            } else {
                                outputData = gSub.sendError(99, "Error encolando proceso...");
                            }
                        }
                        break;
                    case "getPoolProcess":
                        outputData = gSub.sendPoolProcess();
                        break;
                    case "getList":
                        outputData = ""; //gSub.sendList(jData);
                        break;
                    case "updateVar":
                        outputData = ""; //gSub.updateVar(jData);
                        break;
                    default:
                        outputData = gSub.sendError(99, "Error desconocido..");
                    }
                } else {
                    outputData = gSub.sendError(60);
                }
            } catch (IOException | JSONException e) {
                outputData = gSub.sendError(90);
            }

            //Envia Respuesta
            //
            OutputStream outStr = skCliente.getOutputStream();
            DataOutputStream dataOutput = new DataOutputStream(outStr);

            logger.info("Enviando respuesta: " + outputData);

            if (outputData == null) {
                dataOutput.writeUTF("{}");
            } else {
                dataOutput.writeUTF(outputData);
            }

            //Cierra Todas las conexiones
            //
            inpStr.close();
            dataInput.close();
            skCliente.close();
        }

    } catch (NumberFormatException | IOException e) {
        logger.error(e.getMessage());
    }
}

From source file:org.jboss.test.kerberos.KerberosSetup.java

protected void waitForStop() throws Exception {
    final ServerSocket srv = new ServerSocket(SERVER_PORT);
    boolean isStop = false;
    do {//from w  w  w .  j  av  a  2s  .  c o  m
        // Wait for connection from client.
        Socket socket = srv.accept();
        System.out.println("Incomming connection.");
        socket.setSoTimeout(SOCKET_TIMEOUT);
        BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        try {
            isStop = STOP_CMD.equals(rd.readLine());
        } finally {
            rd.close();
        }
        System.out.println("Stop command: " + isStop);
        socket.close();
    } while (!isStop);
    IOUtils.closeQuietly(srv);
}

From source file:com.myapplication.ServerService.java

@Override
protected void onHandleIntent(Intent intent) {
    ServerSocket serverSocket;
    Socket socket;//from  ww  w.  j a v  a 2  s.  co  m
    try {
        serverSocket = new ServerSocket(Constant.SERVER_PORT);
        while (true) {
            //Listen for incoming connections on specified port
            //Block thread until someone connects
            socket = serverSocket.accept();
            clientAddress = socket.getInetAddress().getHostAddress();

            InputStream is = socket.getInputStream();

            String receivedMessage = CommonUtils.getStringFromInputStream(is);
            CommonUtils.showToast(receivedMessage);
            Intent messageIntent = new Intent(Constant.ACTION_MESSAGE_FROM_PEER);
            messageIntent.putExtra(Constant.KEY_MESSAGE_FROM_PEER, receivedMessage);
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(messageIntent);

            socket.close();
        }
    } catch (Exception e) {
        CommonUtils.showToast(e.getMessage());
    }
}

From source file:net.lightbody.bmp.proxy.jetty.http.JsseListener.java

/**
 * @param p_serverSocket/* w ww.j a  v a2  s .  co  m*/
 * @return
 * @exception IOException
 */
protected Socket accept(ServerSocket p_serverSocket) throws IOException {
    try {
        SSLSocket s = (SSLSocket) p_serverSocket.accept();
        if (getMaxIdleTimeMs() > 0)
            s.setSoTimeout(getMaxIdleTimeMs());
        s.startHandshake(); // block until SSL handshaking is done
        return s;
    } catch (SSLException e) {
        log.warn(LogSupport.EXCEPTION, e);
        throw new IOException(e.getMessage());
    }
}

From source file:org.wso2.carbon.membership.scheme.kubernetes.tcpforwarder.TCPForwardServer.java

public void run() {
    ServerSocket listenerSocket;
    try {//from   w  w  w .  j a v a2s.  c o m
        listenerSocket = new ServerSocket(this.sourcePort);
    } catch (IOException e) {
        log.error("Error in starting listener socket in [source-port]: " + this.sourcePort, e);
        return;
    }
    while (isRunning) {
        try {
            Socket clientSocket = listenerSocket.accept();
            ClientThread clientThread = new ClientThread(clientSocket, this.destinationPort, executorService);
            executorService.execute(clientThread);
        } catch (IOException e) {
            log.error("Error in creating client socket", e);
        }
    }
}

From source file:org.mapfish.print.FakeHttpd.java

public void run() {
    try {//from  w w w .  j av a 2  s  .c o m
        LOGGER.info("starting");
        ServerSocket serverSocket = new ServerSocket(port);
        LOGGER.info("started");
        synchronized (starting) {
            starting.set(false);
            starting.notify();
        }

        while (true) {
            Socket socket = serverSocket.accept();
            BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintStream output = new PrintStream(socket.getOutputStream());
            final boolean stayAlive = handleHttp(input, output);
            input.close();
            output.close();
            socket.close();
            if (!stayAlive) {
                break;
            }
        }
        serverSocket.close();
        LOGGER.info("stopped");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.twinsoft.convertigo.eclipse.learnproxy.http.HttpProxy.java

public void run() {
    ServerSocket serverSocket = null;
    try {/*from   www .j a v a  2  s  .com*/
        serverSocket = new ServerSocket(proxyPort);
        serverSocket.setSoTimeout(timeout);
        // logger.info("Proxy started at " + proxyPort);
        while (!isStopped) {
            try {
                Socket sock = serverSocket.accept();
                HttpProxyWorker worker = new HttpProxyWorker(this, sock);
                Thread t = new Thread(worker);
                t.start();
            } catch (IOException e) {
                ConvertigoPlugin.logException(e, "Unexpected exception");
            }
        }
    } catch (IOException e) {
        ConvertigoPlugin.logException(e, "Unexpected exception");
    }
}

From source file:com.web.server.node.NodeServer.java

/**
 * This method implements the node server request
 *///from  www.  j a  v a 2s  . c  om
public void run() {
    ServerSocket serversock = null;
    Socket sock = null;
    try {
        serversock = new ServerSocket(port);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    while (true) {
        try {
            sock = serversock.accept();
            new NodeServerRequestProcessor(sock).start();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:org.apache.geode.internal.net.SSLSocketIntegrationTest.java

private Thread startServer(final ServerSocket serverSocket) throws Exception {
    Thread serverThread = new Thread(new MyThreadGroup(this.testName.getMethodName()), () -> {
        try {/*  ww  w  .  j a  v a  2 s .  co  m*/
            Socket socket = serverSocket.accept();
            SocketCreatorFactory.getSocketCreatorForComponent(CLUSTER).configureServerSSLSocket(socket);
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            messageFromClient.set((String) ois.readObject());
        } catch (IOException | ClassNotFoundException e) {
            throw new Error(e);
        }
    }, this.testName.getMethodName() + "-server");

    serverThread.start();
    return serverThread;
}

From source file:org.wso2.carbon.automation.remotecoverage.CoverageDataServer.java

public void startServer() {
    try {/* w w  w.ja va  2 s .  c  o m*/
        final ExecutionDataWriter fileWriter = new ExecutionDataWriter(
                new FileOutputStream(fileToDumpCoverage));
        final ServerSocket server = new ServerSocket(port, 0, InetAddress.getByName(hostName));

        while (true) {
            log.info("Starting coverage dump server on host " + hostName + " and" + " port " + port);
            log.info("Dumping coverage to : " + fileToDumpCoverage);
            final Handler handler = new Handler(server.accept(), fileWriter);
            new Thread(handler).start();
        }

    } catch (IOException e) {
        log.error("Error while starting coverage dump server", e);
    }
}