类java.net.ServerSocket源码实例Demo

下面列出了怎么用java.net.ServerSocket的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: petscii-bbs   文件: BBServer.java
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();
        }
    }
}
 
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);
    });
}
 
源代码3 项目: datakernel   文件: BlockingSocketServer.java
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();
	}
}
 
源代码4 项目: kop   文件: PortManager.java
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);
            }
        }
    }
}
 
源代码5 项目: dacapobench   文件: SocketFactory.java
/**
 * 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;
    }
}
 
源代码6 项目: openjdk-jdk9   文件: SocksProxy.java
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;
}
 
源代码7 项目: otroslogviewer   文件: SocketLogReader.java
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();

}
 
源代码8 项目: openjdk-8   文件: TCPEndpoint.java
/**
 * 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;
}
 
源代码9 项目: Java-Unserialization-Study   文件: Server.java
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();
        }
    }
}
 
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.");
}
 
源代码11 项目: dragonwell8_jdk   文件: WSTest.java
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);
        }
    }
 
源代码12 项目: tutorials   文件: SimpleServer.java
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!");
            }
        }
    }
}
 
源代码13 项目: openjdk-jdk8u   文件: TCPEndpoint.java
/**
 * 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;
}
 
@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;
    }
  };
}
 
源代码15 项目: jdk8u-jdk   文件: SimpleApplication.java
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();
}
 
源代码16 项目: j2ssh-maverick   文件: ForwardingClient.java
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);
	}
}
 
源代码17 项目: openjdk-8-source   文件: JavacServer.java
/**
 * 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();
}
 
源代码18 项目: jdk8u_jdk   文件: HttpsProxyStackOverflow.java
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;
}
 
public static int findFreePort() {
    try (ServerSocket serverSocket = new ServerSocket(0)) {
        return serverSocket.getLocalPort();
    }
    catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
源代码20 项目: dubbox   文件: SimpleRegistryExporter.java
public synchronized static Exporter<RegistryService> exportIfAbsent(int port) {
    try {
        new ServerSocket(port).close();
        return export(port);
    } catch (IOException e) {
        return null;
    }
}
 
源代码21 项目: ethsigner   文件: ReadTimeoutAcceptanceTest.java
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);
  }
}
 
源代码22 项目: dubbox-hystrix   文件: SimpleRegistryExporter.java
public synchronized static Exporter<RegistryService> exportIfAbsent(int port) {
    try {
        new ServerSocket(port).close();
        return export(port);
    } catch (IOException e) {
        return null;
    }
}
 
源代码23 项目: bidder   文件: FileServer.java
/**
 * 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();
}
 
源代码24 项目: tomee   文件: NetworkUtil.java
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");
}
 
源代码25 项目: dragonwell8_jdk   文件: TestApplication.java
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();
}
 
源代码26 项目: neoscada   文件: NioSocketAcceptor.java
/**
 * {@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;
}
 
源代码27 项目: kelinci   文件: Kelinci.java
/**
 * 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);
	}
}
 
源代码28 项目: journaldev   文件: SocketServerExample.java
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();
}
 
源代码29 项目: openjdk-jdk8u   文件: InvalidLdapFilters.java
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();
}
 
源代码30 项目: netbeans   文件: Utils.java
/** 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;
    }
}
 
 类所在包
 同包方法