Java Code Examples for java.net.ServerSocket

The following examples show how to use java.net.ServerSocket. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: petscii-bbs   Source File: BBServer.java    License: 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 2
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 3
Source Project: datakernel   Source File: BlockingSocketServer.java    License: 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 4
Source Project: kop   Source File: PortManager.java    License: 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 5
Source Project: dacapobench   Source File: SocketFactory.java    License: 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 6
Source Project: openjdk-jdk9   Source File: SocksProxy.java    License: 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 7
Source Project: otroslogviewer   Source File: SocketLogReader.java    License: 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 8
Source Project: openjdk-8   Source File: TCPEndpoint.java    License: 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 Project: Java-Unserialization-Study   Source File: Server.java    License: 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 10
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 11
Source Project: dragonwell8_jdk   Source File: WSTest.java    License: 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 12
Source Project: tutorials   Source File: SimpleServer.java    License: 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 13
Source Project: openjdk-jdk8u   Source File: TCPEndpoint.java    License: 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
@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 Project: jdk8u-jdk   Source File: SimpleApplication.java    License: 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 16
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 17
Source Project: openjdk-8-source   Source File: JavacServer.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Spawn the server instance.
 */

private JavacServer(int poolSize, String logfile) throws IOException {
    serverStart = System.currentTimeMillis();
    // Create a server socket on a random port that is bound to the localhost/127.0.0.1 interface.
    // I.e only local processes can connect to this port.
    serverSocket = new ServerSocket(0, 128, InetAddress.getByName(null));
    compilerPool = new CompilerPool(poolSize, this);
    Random rnd = new Random();
    myCookie = rnd.nextLong();
    theLog = new PrintWriter(logfile);
    log("Javac server started. port=" + getPort() + " date=" + (new java.util.Date()) + " with poolsize=" + poolSize);
    flushLog();
}
 
Example 18
static BadAuthProxyServer startServer() throws IOException {
    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("xyz", "xyz".toCharArray());
        }
        });

    BadAuthProxyServer server = new BadAuthProxyServer(new ServerSocket(0));
    Thread serverThread = new Thread(server);
    serverThread.start();
    return server;
}
 
Example 19
public static int findFreePort() {
    try (ServerSocket serverSocket = new ServerSocket(0)) {
        return serverSocket.getLocalPort();
    }
    catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 20
Source Project: dubbox   Source File: SimpleRegistryExporter.java    License: Apache License 2.0 5 votes vote down vote up
public synchronized static Exporter<RegistryService> exportIfAbsent(int port) {
    try {
        new ServerSocket(port).close();
        return export(port);
    } catch (IOException e) {
        return null;
    }
}
 
Example 21
Source Project: ethsigner   Source File: ReadTimeoutAcceptanceTest.java    License: Apache License 2.0 5 votes vote down vote up
private void close(final ServerSocket socket) {
  try {
    if (!socket.isClosed()) {
      socket.close();
    }
  } catch (final IOException e) {
    LOG.warn("Problem closing unresponsive socket {}", socket.getInetAddress(), e);
  }
}
 
Example 22
Source Project: dubbox-hystrix   Source File: SimpleRegistryExporter.java    License: Apache License 2.0 5 votes vote down vote up
public synchronized static Exporter<RegistryService> exportIfAbsent(int port) {
    try {
        new ServerSocket(port).close();
        return export(port);
    } catch (IOException e) {
        return null;
    }
}
 
Example 23
Source Project: bidder   Source File: FileServer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * A Server that returns unexpired key/data from the database.
 * @param logger Logger. The error logger.
 * @param objects HTreeMap. The map of data on disk.
 * @param port int. The port we will listen for clients to connect.
 * @throws Exception on network and file errors.
 */
public FileServer( Logger logger, HTreeMap objects, int port) throws Exception {
    this.objects = objects;
    this.port = port;
    this.logger = logger;
    ss = new ServerSocket(port);

    logger.info("File server listening on port: {}", port);
    me = new Thread(this);
    me.start();
}
 
Example 24
Source Project: tomee   Source File: NetworkUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static ServerSocket create(final int[] ports) throws IOException {
    for (final int port : ports) {
        try {
            return new ServerSocket(port);
        } catch (final IOException ex) {
            // try next port
        }
    }

    // if the program gets here, no port in the range was found
    throw new IOException("No free port found");
}
 
Example 25
public static void main(String[] args) throws IOException {
    // Some tests require the application to exit immediately
    if (args.length > 0 && args[0].equals("-exit")) {
        return;
    }

    // bind to a random port
    ServerSocket ss = new ServerSocket(0);
    int port = ss.getLocalPort();

    int pid = -1;
    try {
        pid = ProcessTools.getProcessId();
    } catch (Exception e) {
        e.printStackTrace();
    }

    // signal test that we are started - do not remove these lines!!
    System.out.println("port:" + port);
    System.out.println("pid:" + pid);
    System.out.println("waiting for the manager ...");
    System.out.flush();

    // wait for manager to connect
    Socket s = ss.accept();
    s.close();
    ss.close();
}
 
Example 26
Source Project: neoscada   Source File: NioSocketAcceptor.java    License: 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 27
Source Project: kelinci   Source File: Kelinci.java    License: 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 Project: journaldev   Source File: SocketServerExample.java    License: 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 29
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 30
Source Project: netbeans   Source File: Utils.java    License: 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;
    }
}