java.net.ServerSocket Java Examples

The following examples show how to use java.net.ServerSocket. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PortManager.java    From kop with Apache License 2.0 6 votes vote down vote up
public static synchronized int nextFreePort() {
    int exceptionCount = 0;
    while (true) {
        int port = nextPort++;
        try (ServerSocket ss = new ServerSocket(port)) {
            ss.close();
            //Give it some time to truly close the connection
            Thread.sleep(100);
            return port;
        } catch (Exception e) {
            exceptionCount++;
            if (exceptionCount > 5) {
                throw new RuntimeException(e);
            }
        }
    }
}
 
Example #2
Source File: SimpleServer.java    From tutorials with MIT License 6 votes vote down vote up
static void startServer(int port) throws IOException {
    ServerSocketFactory factory = SSLServerSocketFactory.getDefault();

    try (ServerSocket listener = factory.createServerSocket(port)) {
        ((SSLServerSocket) listener).setNeedClientAuth(true);
        ((SSLServerSocket) listener).setEnabledCipherSuites(
          new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"});
        ((SSLServerSocket) listener).setEnabledProtocols(
          new String[] { "TLSv1.2"});
        while (true) {
            try (Socket socket = listener.accept()) {
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                out.println("Hello World!");
            }
        }
    }
}
 
Example #3
Source File: ForwardingClient.java    From j2ssh-maverick with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void start() throws SshException {
	/* Bind server socket */
	try {
		server = new ServerSocket(portToBind, 1000,
				addressToBind.equals("") ? null
						: InetAddress.getByName(addressToBind));

		/* Create a thread and start it */
		thread = new Thread(this);
		thread.setDaemon(true);
		thread.setName("SocketListener " + addressToBind + ":"
				+ String.valueOf(portToBind));
		thread.start();
	} catch (IOException ioe) {
		throw new SshException("Failed to local forwarding server. ",
				SshException.CHANNEL_FAILURE, ioe);
	}
}
 
Example #4
Source File: WSTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        // find a free port
        ServerSocket ss = new ServerSocket(0);
        int port = ss.getLocalPort();
        ss.close();

        Endpoint endPoint1 = null;
        Endpoint endPoint2 = null;
        try {
            endPoint1 = Endpoint.publish("http://0.0.0.0:" + port + "/method1",
                    new Method1());
            endPoint2 = Endpoint.publish("http://0.0.0.0:" + port + "/method2",
                    new Method2());

            System.out.println("Sleep 3 secs...");

            Thread.sleep(3000);
        } finally {
            stop(endPoint2);
            stop(endPoint1);
        }
    }
 
Example #5
Source File: BBServer.java    From petscii-bbs with Mozilla Public License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // args = new String[] {"-b", "MenuRetroAcademy", "-p", "6510"};
    readParameters(args);

    logger.info("{} The BBS {} is running: port = {}, timeout = {} millis",
                new Timestamp(System.currentTimeMillis()),
                bbs.getSimpleName(),
                port,
                timeout);
    try(ServerSocket listener = new ServerSocket(port)) {
        listener.setSoTimeout(0);
        while (true) {
            Socket socket = listener.accept();
            socket.setSoTimeout(timeout);

            CbmInputOutput cbm = new CbmInputOutput(socket);
            PetsciiThread thread = bbs.getDeclaredConstructor().newInstance();
            thread.setSocket(socket);
            thread.setCbmInputOutput(cbm);
            thread.start();
        }
    }
}
 
Example #6
Source File: ProcessAttachDebuggee.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    // bind to a random port
    ServerSocket ss = new ServerSocket(0);
    int port = ss.getLocalPort();

    // Write the port number to the given file
    File partial = new File(args[0] + ".partial");
    File portFile = new File(args[0]);
    try (FileOutputStream fos = new FileOutputStream(partial)) {
        fos.write( Integer.toString(port).getBytes("UTF-8") );
    }
    Files.move(partial.toPath(), portFile.toPath(), StandardCopyOption.ATOMIC_MOVE);

    System.out.println("Debuggee bound to port: " + port);
    System.out.flush();

    // wait for test harness to connect
    Socket s = ss.accept();
    s.close();
    ss.close();

    System.out.println("Debuggee shutdown.");
}
 
Example #7
Source File: Server.java    From Java-Unserialization-Study with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Receive unserialize data from socket, in real world this may be a JBOSS, Web, or others...
    ServerSocket serverSocket = new ServerSocket(9999);
    System.out.println("Server listen on: " + serverSocket.getLocalPort());
    while (true) {
        Socket socket = serverSocket.accept();
        System.out.println("Connection from " + socket.getInetAddress());
        ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
        try {
            Object object = objectInputStream.readObject();
            System.out.println("Read object done. Object: " + object);
        } catch (Exception e) {
            System.out.println("Error when read object!");
            e.printStackTrace();
        }
    }
}
 
Example #8
Source File: TCPEndpoint.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return new server socket to listen for connections on this endpoint.
 */
ServerSocket newServerSocket() throws IOException {
    if (TCPTransport.tcpLog.isLoggable(Log.VERBOSE)) {
        TCPTransport.tcpLog.log(Log.VERBOSE,
            "creating server socket on " + this);
    }

    RMIServerSocketFactory serverFactory = ssf;
    if (serverFactory == null) {
        serverFactory = chooseFactory();
    }
    ServerSocket server = serverFactory.createServerSocket(listenPort);

    // if we listened on an anonymous port, set the default port
    // (for this socket factory)
    if (listenPort == 0)
        setDefaultPort(server.getLocalPort(), csf, ssf);

    return server;
}
 
Example #9
Source File: SocketLogReader.java    From otroslogviewer with Apache License 2.0 6 votes vote down vote up
public void start() throws Exception {
  serverSocket = new ServerSocket(port,50,InetAddress.getByAddress(new byte[]{0,0,0,0}));
  Runnable r = () -> {
    try {
      while (true) {
        Socket s = serverSocket.accept();
        final SocketSource socketSource = new SocketSource(s);
        final LogLoadingSession logLoadingSession = logLoader.startLoading(socketSource, logImporter, logDataCollector);
        loadingSessionSet.add(logLoadingSession);
      }
    } catch (IOException e) {
      if (isClosed()) {
        LOGGER.info("Listening on socket closed.");
      } else {
        LOGGER.warn("Problem with listening on socket: " + e.getMessage());
      }
    }
  };
  Thread t = new Thread(r, "Socket listener");
  t.setDaemon(true);
  t.start();

}
 
Example #10
Source File: SimpleApplication.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
final public void doMyAppStart(String[] args) throws Exception {
    if (args.length < 1) {
        throw new RuntimeException("Usage: " + myAppName +
            " port-file [arg(s)]");
    }

    // bind to a random port
    mySS = new ServerSocket(0);
    myPort = mySS.getLocalPort();

    // Write the port number to the given file
    File f = new File(args[0]);
    FileOutputStream fos = new FileOutputStream(f);
    fos.write( Integer.toString(myPort).getBytes("UTF-8") );
    fos.close();

    System.out.println("INFO: " + myAppName + " created socket on port: " +
        myPort);
    System.out.flush();
}
 
Example #11
Source File: SetFactoryPermission.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void main (String[] args) throws Exception {
    if (args.length > 0) {
        success = System.getSecurityManager() == null || args[0].equals("success");
    }

    doTest(()->{
        System.out.println("Verify URLConnection.setContentHandlerFactor()");
        URLConnection.setContentHandlerFactory(null);
    });
    doTest(()->{
        System.out.println("Verify URL.setURLStreamHandlerFactory()");
        URL.setURLStreamHandlerFactory(null);
    });
    doTest(()->{
        System.out.println("Verify ServerSocket.setSocketFactory()");
        ServerSocket.setSocketFactory(null);
    });
    doTest(()->{
        System.out.println("Verify Socket.setSocketImplFactory()");
        Socket.setSocketImplFactory(null);
    });
    doTest(()->{
        System.out.println("Verify RMISocketFactory.setSocketFactory()");
        RMISocketFactory.setSocketFactory(null);
    });
}
 
Example #12
Source File: SocksProxy.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
static SocksProxy startProxy(Consumer<Socket> socketConsumer)
        throws IOException {
    Objects.requireNonNull(socketConsumer, "socketConsumer cannot be null");

    ServerSocket server
            = ServerSocketFactory.getDefault().createServerSocket(0);

    System.setProperty("socksProxyHost", "127.0.0.1");
    System.setProperty("socksProxyPort",
            String.valueOf(server.getLocalPort()));
    System.setProperty("socksProxyVersion", "4");

    SocksProxy proxy = new SocksProxy(server, socketConsumer);
    Thread proxyThread = new Thread(proxy, "Proxy");
    proxyThread.setDaemon(true);
    proxyThread.start();

    return proxy;
}
 
Example #13
Source File: TCPEndpoint.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return new server socket to listen for connections on this endpoint.
 */
ServerSocket newServerSocket() throws IOException {
    if (TCPTransport.tcpLog.isLoggable(Log.VERBOSE)) {
        TCPTransport.tcpLog.log(Log.VERBOSE,
            "creating server socket on " + this);
    }

    RMIServerSocketFactory serverFactory = ssf;
    if (serverFactory == null) {
        serverFactory = chooseFactory();
    }
    ServerSocket server = serverFactory.createServerSocket(listenPort);

    // if we listened on an anonymous port, set the default port
    // (for this socket factory)
    if (listenPort == 0)
        setDefaultPort(server.getLocalPort(), csf, ssf);

    return server;
}
 
Example #14
Source File: SocketServerRpcConnectionFactoryTest.java    From protobuf-socket-rpc with MIT License 6 votes vote down vote up
@Override
public ServerSocket createServerSocket(int port, int backlog,
    InetAddress ifAddress) throws IOException {
  return new ServerSocket() {

    @Override
    public Socket accept() {
      return socket;
    }

    @Override
    public void close() {
      closed = true;
    }

    @Override
    public boolean isClosed() {
      return closed;
    }
  };
}
 
Example #15
Source File: BlockingSocketServer.java    From datakernel with Apache License 2.0 6 votes vote down vote up
public void start() throws Exception {
	for (InetSocketAddress address : listenAddresses) {
		ServerSocket serverSocket = new ServerSocket(address.getPort(), serverSocketSettings.getBacklog(), address.getAddress());
		serverSocketSettings.applySettings(serverSocket.getChannel());
		serverSockets.add(serverSocket);
		Runnable runnable = () -> {
			while (!Thread.interrupted()) {
				try {
					serveClient(serverSocket.accept());
				} catch (Exception e) {
					if (Thread.currentThread().isInterrupted())
						break;
					logger.error("Socket error for " + serverSocket, e);
				}
			}
		};
		Thread acceptThread = acceptThreadFactory == null ?
				new Thread(runnable) :
				acceptThreadFactory.newThread(runnable);
		acceptThread.setDaemon(true);
		acceptThreads.put(serverSocket, acceptThread);
		acceptThread.start();
	}
}
 
Example #16
Source File: SocketFactory.java    From dacapobench with Apache License 2.0 6 votes vote down vote up
/**
 * Create a server socket for this connection.
 *
 * @param port    The target listener port.
 * @param backlog The requested backlog value for the connection.
 * @param address The host address information we're publishing under.
 *
 * @return An appropriately configured ServerSocket for this
 *         connection.
 * @exception IOException
 * @exception ConnectException
 */
public ServerSocket createServerSocket(int port, int backlog, InetAddress address) throws IOException {
    try {
        // if no protection is required, just create a plain socket.
        if ((NoProtection.value & requires) == NoProtection.value) {
            if (log.isDebugEnabled()) log.debug("Created plain server socket for port " + port);
            return new ServerSocket(port, backlog, address);
        }
        else {
            // SSL is required.  Create one from the SSLServerFactory retrieved from the config.  This will
            // require additional QOS configuration after creation.
            SSLServerSocket serverSocket = (SSLServerSocket)getServerSocketFactory().createServerSocket(port, backlog, address);
            configureServerSocket(serverSocket);
            return serverSocket;
        }
    } catch (IOException ex) {
        log.error("Exception creating a client socket to "  + address.getHostName() + ":" + port, ex);
        throw ex;
    }
}
 
Example #17
Source File: ResourceUtil.java    From sockslib with Apache License 2.0 5 votes vote down vote up
public static void close(InputStream inputStream, OutputStream outputStream, Socket socket,
                         ServerSocket serverSocket) {
  close(inputStream);
  close(outputStream);
  close(socket);
  close(serverSocket);
}
 
Example #18
Source File: Server.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * This attempts to open a free port. We'll search for an open port until we find one.
 *
 * @return the port we opened or -1 if we couldn't open one.
 */
private int connect() {
    try {
        serverSocket = new ServerSocket(0);
        return serverSocket.getLocalPort();
    } catch (IOException e) {
        logger.error("Could not listen on port: " + port, e);
        return -1;
    }
}
 
Example #19
Source File: InvalidLdapFilters.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
void doServerSide() throws Exception {
    ServerSocket serverSock = new ServerSocket(serverPort);

    // signal client, it's ready to accecpt connection
    serverPort = serverSock.getLocalPort();
    serverReady = true;

    // accept a connection
    Socket socket = serverSock.accept();
    System.out.println("Server: Connection accepted");

    InputStream is = socket.getInputStream();
    OutputStream os = socket.getOutputStream();

    // read the bindRequest
    while (is.read() != -1) {
        // ignore
        is.skip(is.available());
        break;
    }

    byte[] bindResponse = {0x30, 0x0C, 0x02, 0x01, 0x01, 0x61, 0x07, 0x0A,
                           0x01, 0x00, 0x04, 0x00, 0x04, 0x00};
    // write bindResponse
    os.write(bindResponse);
    os.flush();

    // ignore any more request.
    while (is.read() != -1) {
        // ignore
        is.skip(is.available());
    }

    is.close();
    os.close();
    socket.close();
    serverSock.close();
}
 
Example #20
Source File: NioSocketAcceptor.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected ServerSocketChannel open(SocketAddress localAddress) throws Exception {
    // Creates the listening ServerSocket
    ServerSocketChannel channel = ServerSocketChannel.open();

    boolean success = false;

    try {
        // This is a non blocking socket channel
        channel.configureBlocking(false);

        // Configure the server socket,
        ServerSocket socket = channel.socket();

        // Set the reuseAddress flag accordingly with the setting
        socket.setReuseAddress(isReuseAddress());

        // and bind.
        socket.bind(localAddress, getBacklog());

        // Register the channel within the selector for ACCEPT event
        channel.register(selector, SelectionKey.OP_ACCEPT);
        success = true;
    } finally {
        if (!success) {
            close(channel);
        }
    }
    return channel;
}
 
Example #21
Source File: SocketServerExample.java    From journaldev with MIT License 5 votes vote down vote up
public static void main(String args[]) throws IOException, ClassNotFoundException{
    //create the socket server object
    server = new ServerSocket(port);
    //keep listens indefinitely until receives 'exit' call or program terminates
    while(true){
        System.out.println("Waiting for client request");
        //creating socket and waiting for client connection
        Socket socket = server.accept();
        //read from socket to ObjectInputStream object
        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        //convert ObjectInputStream object to String
        String message = (String) ois.readObject();
        System.out.println("Message Received: " + message);
        //create ObjectOutputStream object
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
        //write object to Socket
        oos.writeObject("Hi Client "+message);
        //close resources
        ois.close();
        oos.close();
        socket.close();
        //terminate the server if client sends exit request
        if(message.equalsIgnoreCase("exit")) break;
    }
    System.out.println("Shutting down Socket server!!");
    //close the ServerSocket object
    server.close();
}
 
Example #22
Source File: ShutdownMonitor.java    From yawp with MIT License 5 votes vote down vote up
private void listen() {
    try {
        setDaemon(true);
        setName("yawp-devserver-shutdown-monitor");
        socket = new ServerSocket(shutdownPort, 1, InetAddress.getByName("127.0.0.1"));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #23
Source File: Utils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Return true if the specified port is free, false otherwise. */
public static boolean isPortFree(int port) {
    try {
        ServerSocket soc = new ServerSocket(port);
        try {
            soc.close();
        } finally {
            return true;
        }
    } catch (IOException ioe) {
        return false;
    }
}
 
Example #24
Source File: TcpServerLaunch.java    From FimiX8-RE with MIT License 5 votes vote down vote up
public void main() {
    try {
        while (true) {
            Socket s = new ServerSocket(54321).accept();
            mHandler.obtainMessage(0, "start").sendToTarget();
            new TcpServer(s).start();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #25
Source File: IntelliJCoderServer.java    From intellijcoder with MIT License 5 votes vote down vote up
public int start() throws IntelliJCoderException {
    final ServerSocket serverSocket;
    try {
        serverSocket = network.bindServerSocket(0);
    } catch (IOException e) {
        throw new IntelliJCoderException(FAILED_TO_START_SERVER_MESSAGE, e);
    }
    new Thread(new ServerCycle(serverSocket)).start();
    return serverSocket.getLocalPort();
}
 
Example #26
Source File: SSLServerSocketFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ServerSocket
createServerSocket(int port, int backlog, InetAddress ifAddress)
throws IOException
{
    return throwException();
}
 
Example #27
Source File: Kelinci.java    From kelinci with Apache License 2.0 5 votes vote down vote up
/**
 * Method to run in a thread to accept requests coming
 * in over TCP and put them in a queue.
 */
private static void runServer() {

	try (ServerSocket ss = new ServerSocket(port)) {
		if (verbosity > 1)
			System.out.println("Server listening on port " + port);

		while (true) {
			Socket s = ss.accept();
			if (verbosity > 1)
				System.out.println("Connection established.");

			boolean status = false;
			if (requestQueue.size() < maxQueue) {
				status = requestQueue.offer(new FuzzRequest(s));
				if (verbosity > 1)
					System.out.println("Request added to queue: " + status);
			} 
			if (!status) {
				if (verbosity > 1)
					System.out.println("Queue full.");
				OutputStream os = s.getOutputStream();
				os.write(STATUS_QUEUE_FULL);
				os.flush();
				s.shutdownOutput();
				s.shutdownInput();
				s.close();
				if (verbosity > 1)
					System.out.println("Connection closed.");
			}
		}
	} catch (BindException be) {
		System.err.println("Unable to bind to port " + port);
		System.exit(1);
	} catch (Exception e) {
		System.err.println("Exception in request server");
		e.printStackTrace();
		System.exit(1);
	}
}
 
Example #28
Source File: SSLServerSocketFactoryWrapper.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public ServerSocket createServerSocket(int port, int backlog, InetAddress locAddr) throws IOException {
    SSLServerSocket srvSock = (SSLServerSocket)delegate.createServerSocket(port, backlog, locAddr);

    if (parameters != null)
        srvSock.setSSLParameters(parameters);

    return srvSock;
}
 
Example #29
Source File: AcceptCauseFileDescriptorLeak.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    final ServerSocket ss = new ServerSocket(0) {
        public Socket accept() throws IOException {
            Socket s = new Socket() { };
            s.setSoTimeout(10000);
            implAccept(s);
            return s;
        }
    };
    Thread t = new Thread(new Runnable() {
        public void run() {
            try {
                for (int i = 0; i < REPS; i++) {
                    (new Socket("localhost", ss.getLocalPort())).close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    t.start();
    for (int i = 0; i < REPS; i++) {
        ss.accept().close();
    }
    ss.close();
    t.join();
}
 
Example #30
Source File: Race.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    try (ServerSocket ss = new ServerSocket(0)) {
        final int port = ss.getLocalPort();
        final Phaser phaser = new Phaser(THREADS + 1);
        for (int i=0; i<100; i++) {
            final Socket s = new Socket("localhost", port);
            s.setSoLinger(false, 0);
            try (Socket sa = ss.accept()) {
                sa.setSoLinger(false, 0);
                final InputStream is = s.getInputStream();
                Thread[] threads = new Thread[THREADS];
                for (int j=0; j<THREADS; j++) {
                    threads[j] = new Thread() {
                    public void run() {
                        try {
                            phaser.arriveAndAwaitAdvance();
                            while (is.read() != -1)
                                Thread.sleep(50);
                        } catch (Exception x) {
                            if (!(x instanceof SocketException
                                  && x.getMessage().equalsIgnoreCase("socket closed")))
                                x.printStackTrace();
                            // ok, expect Socket closed
                        }
                    }};
                }
                for (int j=0; j<100; j++)
                    threads[j].start();
                phaser.arriveAndAwaitAdvance();
                s.close();
                for (int j=0; j<100; j++)
                    threads[j].join();
            }
        }
    }
}