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:org.apache.tomcat.util.net.puretls.PureTLSSocketFactory.java

public Socket acceptSocket(ServerSocket socket) throws IOException {
    try {/*  w  ww.ja  va 2 s .  c om*/
        Socket sock = socket.accept();
        return sock;
    } catch (SSLException e) {
        logger.debug("SSL handshake error", e);
        throw new SocketException("SSL handshake error" + e.toString());
    }
}

From source file:org.wso2.carbon.membership.scheme.kubernetes.test.MockTCPServer.java

public void run() {
    try {/* w ww  .  j  av  a  2s .c  o m*/
        ServerSocket welcomeSocket = new ServerSocket(TCPForwardTestCase.DESTINATION_PORT);
        log.info("Mock TCP Server starting at port: " + TCPForwardTestCase.DESTINATION_PORT);
        while (true) {
            final Socket connectionSocket = welcomeSocket.accept();
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    handleClientRequest(connectionSocket);
                }
            };
            executorService.execute(runnable);
        }
    } catch (IOException e) {
        log.error(e);
    }
}

From source file:ca.uhn.hunit.example.MllpHl7v2MessageSwapper.java

@Override
public void run() {
    Socket socket = null;/*  w  w w  . j ava  2  s .  c  o  m*/

    try {
        if (myPrintOutput) {
            System.out.println("Opening server socket on port " + 10201);
        }

        ServerSocket serverSocket = new ServerSocket(10201);

        socket = serverSocket.accept();

        InputStream inputStream = socket.getInputStream();
        inputStream = new BufferedInputStream(inputStream);

        MinLLPReader minLLPReader = new MinLLPReader(inputStream);

        Socket outSocket = null;

        if (myPrintOutput) {
            System.out.println("Accepting connection from " + socket.getInetAddress().getHostAddress());
        }

        for (int i = 0; i < myIterations; i++) {
            String messageText;

            do {
                messageText = minLLPReader.getMessage();
                Thread.sleep(250);
            } while (messageText == null);

            if (myPrintOutput) {
                System.out.println("Received message:\r\n" + messageText + "\r\n");
            }

            MSH inboundHeader = (MSH) myParser.parse(messageText).get("MSH");
            String controlId = inboundHeader.getMessageControlID().encode();
            if (StringUtils.isNotBlank(controlId) && myControlIdsToIgnore.indexOf(controlId) > -1) {
                Message replyAck = DefaultApplication.makeACK(inboundHeader);
                new MinLLPWriter(socket.getOutputStream()).writeMessage(myParser.encode(replyAck));
            } else {
                System.out.println("Ignoring message with control ID " + controlId);
            }

            for (Map.Entry<String, String> next : mySubstitutions.entrySet()) {
                messageText = messageText.replace(next.getKey(), next.getValue());
            }

            if ((outSocket != null) && myAlwaysCreateNewOutboundConnection) {
                outSocket.close();
                outSocket = null;
            }

            if (outSocket == null) {
                if (myPrintOutput) {
                    System.out.println("Opening outbound connection to port " + 10200);
                }

                outSocket = new Socket();
                outSocket.connect(new InetSocketAddress("localhost", 10200));
            }

            if (myPrintOutput) {
                System.out.println("Sending message from port " + outSocket.getLocalPort() + ":\r\n"
                        + messageText + "\r\n");
            }

            new MinLLPWriter(outSocket.getOutputStream()).writeMessage(messageText);
            new MinLLPReader(outSocket.getInputStream()).getMessage();
        }

        serverSocket.close();
        socket.close();

        myStopped = true;

    } catch (Exception e) {
        myStopped = true;
        e.printStackTrace();
    }
}

From source file:disko.flow.analyzers.socket.SocketReceiver.java

private Message readMessage(ServerSocket serverSocket) {
    while (true) {
        Socket clientSocket = null;
        ObjectInputStream in = null;
        try {//ww w. j  a  va2s .com
            clientSocket = serverSocket.accept();
            in = new ObjectInputStream(clientSocket.getInputStream());
            Message message = null;
            try {
                message = (Message) in.readObject();
            } catch (IOException e) {
                log.error("Error reading object.", e);
                continue;
            } catch (ClassNotFoundException e) {
                log.error("Class not found.", e);
                continue;
            }
            // while (in.read() != -1);
            // if (in.available() > 0)
            // {
            // System.err.println("OOPS, MORE THAT ON SOCKET HASN'T BEEN
            // READ: " + in.available());
            // while (in.available() > 0)
            // in.read();
            // }
            return message;
        } catch (SocketTimeoutException ex) {
            if (Thread.interrupted())
                return null;
        } catch (InterruptedIOException e) // this doesn't really work, that's why we put an Socket timeout and we check for interruption
        {
            return null;
        } catch (IOException e) {
            log.error("Could not listen on port: " + port, e);
        } finally {
            if (in != null)
                try {
                    in.close();
                } catch (Throwable t) {
                    log.error("While closing receiver input.", t);
                }
            if (clientSocket != null)
                try {
                    clientSocket.close();
                } catch (Throwable t) {
                    log.error("While closing receiver socket.", t);
                }
        }
    }
}

From source file:com.joliciel.talismane.TalismaneServerImpl.java

@Override
public void process() {
    try {/*w w w . ja  v a 2s  .c  om*/
        // ping the lexicon to load it
        TalismaneSession.getLexicon();
        LOG.debug("Starting server");

        ServerSocket serverSocket = new ServerSocket(port);
        while (listening) {
            TalismaneServerThread thread = new TalismaneServerThread(this, config, serverSocket.accept());
            thread.setTalismaneService(this.getTalismaneService());
            thread.start();
        }
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:com.yahoo.gondola.cli.GondolaAgent.java

/**
 * Instantiates a new Gondola agent./*from w w  w  .j av  a2 s  . c  o m*/
 *
 * @param port the port
 * @throws IOException the io exception
 */
public GondolaAgent(int port) throws IOException {
    ServerSocket serversocket = new ServerSocket(port);
    logger.info("Listening on port " + port);
    Socket socket;
    while ((socket = serversocket.accept()) != null) {
        new Handler(socket).start();
    }
}

From source file:org.svenk.redmine.core.client.RedmineAbstractClientConcurrancyTest.java

protected void setUp() throws Exception {
    super.setUp();

    location = new WebLocation(URI, "jsmith", "jsmith");
    repository = new TaskRepository(RedmineCorePlugin.REPOSITORY_KIND, URI);

    firstMethod = new GetMethod(URI);
    secondMethod = new GetMethod(URI);

    testee = new ClientTestImpl(location, repository);

    serverThread = new Thread(new Runnable() {
        @Override/*w ww  . j av a2  s  .  c  om*/
        public void run() {
            try {
                ServerSocket server = new ServerSocket(1234);
                while (!Thread.interrupted()) {
                    Socket socket = server.accept();

                    socket.getInputStream().read(new byte[4096]);
                    socket.getOutputStream().write(RESPONSE_HEADER.getBytes());
                    socket.getOutputStream().write(TEST_STRING.getBytes());
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    });

    serverThread.start();
}

From source file:org.mule.test.firewall.FirewallTestCase.java

protected void doTestTcp(InetAddress address, int port) throws Exception {
    try {/*from w  w  w  .  ja va2 s .  c  om*/
        logger.debug("Testing TCP on " + addressToString(address, port));
        ServerSocket server = openTcpServer(address, port);
        Socket client = openTcpClient(address, port);
        Socket receiver = server.accept();
        client.getOutputStream().write(1);
        assertEquals("Failed to send byte via " + addressToString(address, port), 1,
                receiver.getInputStream().read());
        client.close();
        server.close();
    } catch (Exception e) {
        logger.error("Error while attempting TCP message on " + addressToString(address, port));
        throw e;
    }
}

From source file:com.replaymod.replaystudio.launcher.DaemonLauncher.java

public void launch(CommandLine cmd) throws Exception {
    int threads = Integer.parseInt(cmd.getOptionValue('d', "" + Runtime.getRuntime().availableProcessors()));
    worker = Executors.newFixedThreadPool(threads);

    System.setOut(new PrintStream(systemOut = new ThreadLocalOutputStream(System.out)));
    ServerSocket serverSocket = new ServerSocket(PORT);
    System.out.println("Daemon started on port " + PORT + " with " + threads + " worker threads.");
    while (!Thread.interrupted()) {
        Socket socket = serverSocket.accept();
        try {/* w  w w.j  a  v a 2  s. c om*/
            Client client = new Client(socket);
            new Thread(client).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.reficio.cougar.impl.ConnectionFactoryTest.java

private int startMockServer() {
    final int port = TestUtil.getFreePort();
    final CountDownLatch latch = new CountDownLatch(1);
    Runnable runnable = new Runnable() {
        public void run() {
            try {
                ServerSocket srv = new ServerSocket(port, 0, InetAddress.getByName(null));
                latch.countDown();//  www.j  av  a 2  s  . c o m
                try {
                    srv.setSoTimeout(15000);
                    Socket comm = srv.accept();
                    Frame response = new Frame(Command.CONNECTED);
                    response.session(UUID.randomUUID().toString());
                    StompWireFormat wireFormat = new WireFormatImpl();
                    OutputStream out = comm.getOutputStream();
                    Writer writer = new OutputStreamWriter(out);
                    wireFormat.marshal(response, writer);
                    writer.close();
                } finally {
                    srv.close();
                }
            } catch (IOException e) {
                log.error("IO exception", e);
            }
        }
    };
    Thread thread = new Thread(runnable);
    thread.start();
    try {
        latch.await();
    } catch (InterruptedException e) {
    }
    return port;
}