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:SimpleHttpServerDataProvider.java

public SimpleHttpServer(SimpleHttpServerDataProvider dataProvider, int port) {

    class SocketProcessor implements Runnable {
        private Socket s;
        private InputStream is;
        private OutputStream os;
        private SimpleHttpServerDataProvider dataProvider;

        private SocketProcessor(Socket s, SimpleHttpServerDataProvider prov) throws Throwable {
            this.dataProvider = prov;
            this.s = s;
            this.is = s.getInputStream();
            this.os = s.getOutputStream();
        }//from ww w.  j  a va2  s  . c  om

        public void run() {
            try {
                readInputHeaders();
                writeResponse("");
            } catch (Throwable t) {
                /*do nothing*/
            } finally {
                try {
                    s.close();
                } catch (Throwable t) {
                    /*do nothing*/
                }
            }

        }

        private void writeResponse(String s) throws Throwable {
            String response = "HTTP/1.1 200 OK\r\n" + "Server: DJudge.http\r\n" + "Content-Type: text/html\r\n"
                    + "Content-Length: " + s.length() + "\r\n" + "Connection: close\r\n\r\n";
            String result = response + dataProvider.getHtmlPage("");
            os.write(result.getBytes());
            os.flush();
        }

        private void readInputHeaders() throws Throwable {
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            while (true) {
                String s = br.readLine();
                if (s == null || s.trim().length() == 0) {
                    break;
                }

            }
        }
    }

    this.dataProvider = dataProvider;
    try {
        ServerSocket ss = new ServerSocket(port);

        while (true) {
            Socket s = ss.accept();

            new Thread(new SocketProcessor(s, dataProvider)).start();
        }
    } catch (Exception e) {

    } catch (Throwable e) {

    }
}

From source file:csparql_shim.SocketStream.java

/**
 * start listening on a socket and forwarding to csparql
 * stream in defined windows to allow comparison with cqels
 *///from www  . j  av a  2 s  . co m
@Override
public void run() {
    ServerSocket ssock = null;
    Socket sock = null;
    try {
        ssock = new ServerSocket(this.port);
        sock = ssock.accept();

        DataInputStream is = new DataInputStream(sock.getInputStream());
        JSONParser parser = new JSONParser();

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;

        int windowcount = 1;

        //loop for streaming in data
        while ((line = reader.readLine()) != null && !stop) {

            try {
                Object obj = parser.parse(line);
                JSONArray array = (JSONArray) obj;

                //stream the triple
                final RdfQuadruple q = new RdfQuadruple((String) array.get(0), (String) array.get(1),
                        (String) array.get(2), System.currentTimeMillis());
                this.put(q);
                System.out.println("triple sent at: " + System.currentTimeMillis());
            } catch (ParseException pe) {
                System.err.println("Error when parsing input, incorrect JSON.");
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:cqels_shim.SocketStream.java

/**
 * start listening on the socket and forwarding to cqels
 *//*from w  ww  . j a va2  s. c om*/
public void run() {
    ServerSocket ssock = null;
    Socket sock = null;
    try {
        ssock = new ServerSocket(this.port);
        sock = ssock.accept();

        DataInputStream is = new DataInputStream(sock.getInputStream());

        JSONParser parser = new JSONParser();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;

        while ((line = reader.readLine()) != null && !stop) {
            try {
                Object obj = parser.parse(line);
                JSONArray array = (JSONArray) obj;

                //stream the triple
                stream(n((String) array.get(0)), n((String) array.get(1)), n((String) array.get(2)));
            } catch (ParseException pe) {
                System.err.println("Error when parsing input, incorrect JSON.");
            }

            if (sleep > 0) {
                try {
                    Thread.sleep(sleep);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.miraclelinux.historygluon.ConnectionThread.java

@Override
public void run() {
    ServerSocket server = null;
    try {//from   w  w  w.  ja va 2s  .  co m
        server = new ServerSocket(m_port);
        m_log.info("start listening on port: " + server.getLocalPort());
        while (true) {
            Socket client = server.accept();
            StorageDriver driver = m_driver.createInstance();
            BridgeWorker bridge = new BridgeWorker(client, driver);
            bridge.start();
        }
    } catch (Exception e) {
        e.printStackTrace();
        m_log.error(e);
    }
}

From source file:org.jfree.chart.demo.SocketThread.java

@Override
public void run() {
    // TODO Auto-generated method stub
    try {/*  w  w w  .ja va  2 s .  com*/
        ServerSocket ss = new ServerSocket(4444);
        Socket socket = null;
        while (Islive) {
            System.out.println("Started :) ");
            socket = ss.accept(); /*  */
            System.out.println("Got a client :) ");

            InputStream sin = socket.getInputStream();
            OutputStream sout = socket.getOutputStream();

            in = new DataInputStream(sin);
            out = new DataOutputStream(sout);

            String line = null;

            while (true) {
                line = in.readUTF(); /*    */
                System.out.println("line start sending  = " + line);
                out.writeUTF(data);
                out.flush();
                line = in.readUTF();
                System.out.println(line);
                if (line == "finish")
                    break;
                else {
                    out.writeUTF("ok");
                    out.flush();
                }
            }
        }
        out.writeUTF("finish");
        out.flush();

        in.close();
        out.close();
        socket.close();
    } catch (Exception x) {

        errors += x.toString() + " ;\n";
        error_flag = true;
    }

}

From source file:org.nuxeo.box.api.test.BoxBaseTest.java

protected String getCode() throws IOException {
    ServerSocket serverSocket = new ServerSocket(PORT);
    Socket socket = serverSocket.accept();
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    while (true) {
        String code = StringUtils.EMPTY;
        code = in.readLine();//from w  w w.  j a v  a 2s  . com
        String match = "code";
        int loc = code.indexOf(match);
        if (loc > 0) {
            int httpstr = code.indexOf("HTTP") - 1;
            code = code.substring(code.indexOf(match), httpstr);
            String parts[] = code.split("=");
            code = parts[1];
        }
        return code;
    }
}

From source file:cnxchecker.Server.java

public void doit() {
    try {/* ww w .ja va 2 s .  c o m*/
        ServerSocket ss = new ServerSocket(port);
        System.out.println("[INFO] Listenning on " + ss);
        while (true) {
            try {
                Socket s = ss.accept();
                Thread handler = new ClientHandler(s);
                handler.start();
            } catch (IOException e) {
                printAndExit("Failed to accept a new client: " + e.getMessage());
            }
        }
    } catch (IOException e) {
        printAndExit("Failed to bind to " + port + ": " + e.getMessage());
    }
}

From source file:org.apache.ftpserver.socketfactory.FtpSocketFactoryTest.java

private void testCreateServerSocket(final FtpSocketFactory ftpSocketFactory, final int port)
        throws Exception, IOException {
    boolean freePort = false;
    try {//  w  ww .j  ava2s .c  o  m
        final ServerSocket testSocket = new ServerSocket(port, 100);
        freePort = testSocket.isBound();
        testSocket.close();
    } catch (Exception exc) {
        // ok
        freePort = true;
    }
    if (freePort) {
        new Thread() {
            public void run() {
                synchronized (this) {
                    try {
                        this.wait(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        fail(e.toString());
                    }
                }
                try {
                    Socket socket = new Socket();
                    socket.connect(new InetSocketAddress("localhost", port));
                    socket.getInputStream();
                    socket.getOutputStream();
                    socket.close();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                    fail(e.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                    fail(e.toString());
                }
            }
        }.start();
        ServerSocket serverSocket = ftpSocketFactory.createServerSocket();
        assertNotNull(serverSocket);
        serverSocket.accept();
    }
}

From source file:quarks.freeautomaticbridg.CommunicationServer.java

public void startServer(int port) throws IOException, InterruptedException {

    //init CommunicationSubsystems

    for (String subSys : this.communicationSubSystems.keySet()) {
        CommunicationSubSystem comSub = this.communicationSubSystems.get(subSys);
        Thread workingQue = new Thread(comSub);
        workingQue.start();/* w ww. ja  va  2s  .c  o  m*/
    }

    log.info("Start listening on port " + port);

    ServerSocket server = new ServerSocket(port);

    while (true) {
        Socket socket = server.accept();

        HtmlGetRequestHandler htmlHandler = new HtmlGetRequestHandler(socket, this);

        Thread thread = new Thread(htmlHandler);
        thread.start();
        Thread.sleep(5);

    }
}

From source file:org.apache.solr.update.DocumentProcessor.java

/**
 * Send the data//from w w  w  .  j  ava2 s .c  o  m
 * @param data
 */
void serveData(String data) {
    try {
        ServerSocket srvr = new ServerSocket(thePort);
        System.out.println("DocumentProcessor socket " + srvr);
        Socket skt = srvr.accept();
        System.out.print("Server has connected!\n");
        PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
        System.out.print("Sending string: '" + data + "'\n");
        out.print(data);
        out.close();
        skt.close();
        srvr.close();
    } catch (Exception e) {
        System.out.print("Whoops! It didn't work!\n");
        e.printStackTrace();
        //TODO figure out how to get this into Solr's logging system
    }
}