Example usage for javax.net ServerSocketFactory createServerSocket

List of usage examples for javax.net ServerSocketFactory createServerSocket

Introduction

In this page you can find the example usage for javax.net ServerSocketFactory createServerSocket.

Prototype

public abstract ServerSocket createServerSocket(int port) throws IOException;

Source Link

Document

Returns a server socket bound to the specified port.

Usage

From source file:SSLSimpleServer.java

public static void main(String[] args) throws Exception {
    ServerSocketFactory ssf = SSLServerSocketFactory.getDefault();
    ServerSocket ss = ssf.createServerSocket(9096);

    System.out.println("Ready...");
    while (true) {
        new SSLSimpleServer(ss.accept()).start();
    }/*w w  w.j  a  va 2s.  c om*/
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
      ServerSocketFactory ssf = SSLServerSocketFactory.getDefault();
      ServerSocket ss = ssf.createServerSocket(9096);

      while (true) {
          new SSLSimpleServer(ss.accept()).start();
      }// w ww . ja va  2 s.  co  m
  }

From source file:SecureServer.java

public static void main(String[] args) throws Exception {
    ServerSocketFactory ssf = SSLServerSocketFactory.getDefault();
    SSLServerSocket ss = (SSLServerSocket) ssf.createServerSocket(98999);
    Socket sock = ss.accept();//from  ww w.jav  a2  s. com
    ss.close();
    OutputStream rawOut = sock.getOutputStream();
    PrintWriter out = new PrintWriter(new OutputStreamWriter(rawOut));
    out.println(new java.util.Date().toString());
    out.flush();
    sock.close();

}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    int port = 443;
    ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault();
    ServerSocket ssocket = ssocketFactory.createServerSocket(port);

    Socket socket = ssocket.accept();

    InputStream in = socket.getInputStream();
    OutputStream out = socket.getOutputStream();

    // Read from in and write to out...

    in.close();//w  ww  .j av  a  2 s . c  o m
    out.close();
}

From source file:de.hshannover.f4.trust.iron.mapserver.contentauth.RemotePDP.java

private static void runServer(int port, LocalSunXacml pdp, int threads) {
    Executor clientExec = Executors.newFixedThreadPool(threads);
    ServerSocketFactory sockFac = ServerSocketFactory.getDefault();

    try {//from ww w  .  ja  v  a  2  s.  com
        ServerSocket sock = sockFac.createServerSocket(port);
        while (true) {
            Socket clientSock = sock.accept();
            Runnable cmd = new HandleXacmlRequest(clientSock, pdp);
            System.out.println(nameDate() + "new client " + clientSock.getInetAddress());
            clientExec.execute(cmd);
        }
    } catch (IOException e) {
        System.err.println(nameDate() + e.toString());
        System.exit(1);
    }
}

From source file:com.aol.advertising.qiao.util.CommonUtils.java

public static ServerSocket createServerSocket(int startPort, int endPort) throws BindException {
    ServerSocket ssoc = null;/*from w  w w  .  j  a  v a 2s .  c om*/
    ServerSocketFactory factory = ServerSocketFactory.getDefault();

    int port = startPort;
    while (true) {
        try {
            ssoc = factory.createServerSocket(port);
            break;
        } catch (IOException e) {
            if (port >= endPort)
                throw new BindException(
                        "No available port to bind to in range [" + startPort + " .. " + endPort + "]");
            port++;
        }
    }

    return ssoc;
}

From source file:com.alecgorge.minecraft.jsonapi.NanoHTTPD.java

/**
 * Starts a HTTP server to given port.//from   w  w  w . j a va2s.co  m
 * <p>
 * Throws an IOException if the socket is already in use
 */
public NanoHTTPD(int port, boolean ssl, InetAddress bindAddress) throws IOException {
    myTcpPort = port;

    if (ssl) {
        ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault();
        myServerSocket = ssocketFactory.createServerSocket(port);
    } else {
        if (bindAddress != null) {
            myServerSocket = new ServerSocket(myTcpPort, /* default value */-1, bindAddress);
        } else {
            myServerSocket = new ServerSocket(myTcpPort);
        }
    }
    myThread = new Thread(new Runnable() {
        public void run() {
            try {
                while (true)
                    new HTTPSession(myServerSocket.accept());
            } catch (IOException ioe) {
            }
        }
    });
    myThread.setDaemon(true);
    myThread.start();
}

From source file:org.jets3t.service.FakeS3Server.java

/**
 * @param args//from  w  ww . j a v a 2s .  c  om
 */
public static void main(String[] args) throws Exception {
    AWSCredentials fakeAwsCredentials = new AWSCredentials("fake-aws-access-key", "fake-aws-secret-key");

    int port = 443;
    ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault();
    ServerSocket ssocket = ssocketFactory.createServerSocket(port);
    System.out.println("Accepting connections on port 443");

    while (port == 443) {
        // Listen for connections
        Socket socket = ssocket.accept();
        System.out.println("Opened connection");

        // Create streams to securely send and receive data to the client
        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();

        byte[] buffer = new byte[1024];
        int read;

        while ((read = in.read(buffer)) != -1) {
            String receivedDataStr = new String(buffer, 0, read);
            String requestActionAndHeaders = receivedDataStr.substring(0,
                    receivedDataStr.indexOf("\r\n\r\n") + 4);

            System.out.println(requestActionAndHeaders);

            if (requestActionAndHeaders.startsWith("GET")) {
                String path = requestActionAndHeaders.substring(4, requestActionAndHeaders.indexOf(' ', 4));

                if (path.startsWith("/jets3t-")) {
                    // Return fake AWS credentials.
                    String headers = "HTTP/1.1 200 OK\r\n" + "x-amz-id-2: FakeAWSCredentials\r\n"
                            + "x-amz-request-id: FakeAWSCredentials\r\n"
                            + "Date: Thu, 24 May 2007 13:39:21 GMT\r\n" + "Cache-Control: max-age=259200\r\n"
                            + "Last-Modified: Wed, 27 Dec 2006 02:37:58 GMT\r\n"
                            + "ETag: \"fa5d6b0ea9716cf692b286b6aa187f3d\"\r\n"
                            + "Content-Type: application/octet-stream\r\n" + "Content-Length: 139\r\n"
                            + "Server: AmazonS3\r\n\r\n";

                    out.write(headers.getBytes("UTF-8"));
                    fakeAwsCredentials.save("please", out);
                }

                else if (path.equals("/")) {
                    // Return fake bucket listing.
                    String headers = "HTTP/1.1 200 OK\r\n" + "x-amz-id-2: FakeBucketListing\r\n"
                            + "x-amz-request-id: FakeBucketListing\r\n"
                            + "Date: Thu, 24 May 2007 13:39:23 GMT\r\n" + "Content-Type: application/xml\r\n"
                            + "Transfer-Encoding: chunked\r\n" + "Server: AmazonS3\r\n\r\n";

                    String bucketListing = "17b\r\n" + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                            + "<ListAllMyBucketsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">"
                            + "<Owner><ID>1a405254c932b52e5b5caaa88186bc431a1bacb9ece631f835daddaf0c47677c</ID>"
                            + "<DisplayName>jamesmurty</DisplayName></Owner>"
                            + "<Buckets><Bucket><Name>TestUploadBucket</Name>"
                            + "<CreationDate>2006-12-13T21:21:14.000Z</CreationDate>"
                            + "</Bucket></Buckets></ListAllMyBucketsResult>" + "\r\n0\r\n\r\n";

                    out.write(headers.getBytes("UTF-8"));
                    out.write(bucketListing.getBytes("UTF-8"));
                }

                else if (path.startsWith("/TestUploadBucket")) {
                    // Return empty bucket contents

                    String headers = "HTTP/1.1 200 OK\r\n" + "x-amz-id-2: FakeBucketContents\r\n"
                            + "x-amz-request-id: FakeBucketContents\r\n"
                            + "Date: Thu, 24 May 2007 13:39:23 GMT\r\n" + "Content-Type: application/xml\r\n"
                            + "Transfer-Encoding: chunked\r\n" + "Server: AmazonS3\r\n\r\n";

                    String bucketContents = "f2\r\n" + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                            + "<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">"
                            + "<Name>TestUploadBucket</Name><Prefix></Prefix><Marker></Marker>"
                            + "<MaxKeys>1000</MaxKeys><IsTruncated>false</IsTruncated>" + "</ListBucketResult>"
                            + "\r\n0\r\n\r\n";

                    out.write(headers.getBytes("UTF-8"));
                    out.write(bucketContents.getBytes("UTF-8"));
                }

                else {
                    System.out.println("ERROR: Unrecognised GET request");
                }

            } else if (requestActionAndHeaders.startsWith("PUT")) {
                long contentLength = 0;
                String clientProvidedHash = "NONE";

                // Determine content length.
                int searchIndex = requestActionAndHeaders.indexOf("Content-Length: ")
                        + "Content-Length: ".length();
                contentLength = (new Long(requestActionAndHeaders.substring(searchIndex,
                        requestActionAndHeaders.indexOf('\r', searchIndex)))).longValue();

                // Determine content MD5 (hex encoded).
                searchIndex = requestActionAndHeaders.indexOf("Content-MD5: ") + "Content-MD5: ".length();
                if (searchIndex >= -1) {
                    clientProvidedHash = requestActionAndHeaders.substring(searchIndex,
                            requestActionAndHeaders.indexOf('\r', searchIndex));
                }

                // Read all PUT data provided by client, generating an MD5 hash as we go.
                System.out.println("Receiving " + contentLength + " bytes from client");
                MessageDigest digest = MessageDigest.getInstance("MD5");

                long putdataAlreadyRead = read - requestActionAndHeaders.length(); // read - (requestActionAndHeaders.lastIndexOf("\r\n") + 2);
                digest.update(buffer, (int) (read - putdataAlreadyRead), (int) putdataAlreadyRead);

                byte[] putdata = new byte[8192];
                int putdataRead = 0;
                while ((putdataRead = in.read(putdata)) != -1) {
                    digest.update(putdata, 0, putdataRead);
                    putdataAlreadyRead += putdataRead;

                    if (putdataAlreadyRead == contentLength) {
                        System.out.println("PUT object upload is complete");
                        break;
                    }
                }

                if (putdataAlreadyRead != contentLength) {
                    System.err.println(
                            "ERROR: Expected " + contentLength + " bytes but received " + putdataAlreadyRead);
                    continue;
                }

                String receivedDataHashAsHex = new String(Base64.encodeBase64(digest.digest()), "UTF-8");

                // Generate the headers appropriate for the PUT object.
                String headers = "HTTP/1.1 200 OK\r\n" + "x-amz-id-2: FakePUT\r\n"
                        + "x-amz-request-id: FakePUT\r\n" + "Date: Thu, 24 May 2007 15:12:30 GMT\r\n"
                        + "ETag: \"" + receivedDataHashAsHex + "\"\r\n" + "Content-Length: 0\r\n"
                        + "Server: AmazonS3\r\n\r\n";
                out.write(headers.getBytes("UTF-8"));
                out.flush();

                // Compare expected hash (supplied by client) verses actual hash (for retrieved data)
                if (!receivedDataHashAsHex.equals(clientProvidedHash)) {
                    System.err.println("ERROR: Client-side hash " + clientProvidedHash
                            + " does not match hash of received data " + receivedDataHashAsHex);
                } else {
                    System.out.println("SUCCESS: Client-side hash matches hash of received data: "
                            + receivedDataHashAsHex);
                }

            } else {
                System.out.println("ERROR: Unrecognised input");
            }
        }
        // Close the socket
        System.out.println("Closing connection");
        in.close();
        out.close();
    }
}

From source file:org.wso2.carbon.databridge.receiver.binary.BinaryDataReceiver.java

private void startEventTransmission() throws IOException {
    ServerSocketFactory serversocketfactory = ServerSocketFactory.getDefault();
    ServerSocket serversocket = serversocketfactory
            .createServerSocket(binaryDataReceiverConfiguration.getTCPPort());
    for (int i = 0; i < binaryDataReceiverConfiguration.getSizeOfTCPThreadPool(); i++) {
        tcpReceiverExecutorService.submit(new BinaryTransportReceiver(serversocket));
    }/*from  w  ww  . j av a2  s  . c  o  m*/
    log.info("Started Binary TCP Transport on port : " + binaryDataReceiverConfiguration.getTCPPort());
}

From source file:org.wso2.carbon.databridge.receiver.binary.internal.BinaryDataReceiver.java

private void startEventTransmission() throws IOException {
    ServerSocketFactory serversocketfactory = ServerSocketFactory.getDefault();
    ServerSocket serversocket = serversocketfactory
            .createServerSocket(binaryDataReceiverConfiguration.getTCPPort());
    Thread thread = new Thread(new BinaryEventServerAcceptor(serversocket));
    thread.start();//from  ww  w  . j av a2s.  c o  m
    log.info("Started Binary TCP Transport on port : " + binaryDataReceiverConfiguration.getTCPPort());
}