Java Code Examples for java.net.ServerSocket#accept()

The following examples show how to use java.net.ServerSocket#accept() . 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: ServerSocketTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testTimeoutAfterAccept() throws Exception {
    final ServerSocket ss = new ServerSocket(0);
    ss.setReuseAddress(true);
    // On Unix, the receive timeout is inherited by the result of accept(2).
    // Java specifies that it should always be 0 instead.
    ss.setSoTimeout(1234);
    final Socket[] result = new Socket[1];
    Thread t = new Thread(new Runnable() {
        public void run() {
            try {
                result[0] = ss.accept();
            } catch (IOException ex) {
                ex.printStackTrace();
                fail();
            }
        }
    });
    t.start();
    new Socket(ss.getInetAddress(), ss.getLocalPort());
    t.join();
    assertEquals(0, result[0].getSoTimeout());
}
 
Example 2
Source File: Streams.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
static void runTest(Class<? extends StreamGetter> klass, ServerSocket ss)
    throws Exception
{
    final int port = ss.getLocalPort();
    Socket[] sockets = new Socket[NUM_THREADS];
    for (int i=0; i<NUM_THREADS; i++) {
        sockets[i] = new Socket("localhost", port);
        try (Socket socket = ss.accept()) {}
    }

    Constructor<? extends StreamGetter> ctr = klass.getConstructor(Socket.class);

    Thread[] threads = new Thread[NUM_THREADS];
    for (int i=0; i<NUM_THREADS; i++)
        threads[i] = ctr.newInstance(sockets[i]);
    for (int i=0; i<NUM_THREADS; i++)
        threads[i].start();

    startingGate.arriveAndAwaitAdvance();
    for (int i=0; i<NUM_THREADS; i++)
        sockets[i].close();

    for (int i=0; i<NUM_THREADS; i++)
        threads[i].join();
}
 
Example 3
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 4
Source File: ConnectionDispatcherRunable.java    From bboxdb with Apache License 2.0 6 votes vote down vote up
@Override
public void runThread() {
	try {
		serverSocket = new ServerSocket(port);
		serverSocket.setReuseAddress(true);

		while(isThreadActive()) {
			final Socket clientSocket = serverSocket.accept();
			handleConnection(clientSocket);
		}

	} catch(IOException e) {

		// Print exception only if the exception is really unexpected
		if(isThreadActive()) {
			logger.error("Got an IO exception while reading from server socket ", e);
		}

	} finally {
		closeSocketNE();
	}
}
 
Example 5
Source File: ANSIMonitor.java    From swift-k with Apache License 2.0 6 votes vote down vote up
public void run() {
	try {
		disp = new LocalANSIDisplay(this);
		disp.start();
		if (port != 0) {
   			socket = new ServerSocket(port);
   			while (true) {
   				Socket s = socket.accept();
   				RemoteANSIConnection c = new RemoteANSIConnection(this, s);
   				synchronized (connections) {
   					connections.add(c);
   				}
   				c.start();
   			}
		}
	}
	catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 6
Source File: FdfsMockSocketServer.java    From FastDFS_Client with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void run() {
    try {
        serverSocket = new ServerSocket(PORT);
        LOGGER.debug("[MockServer]start mock server for test..{}", serverSocket);
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    while (!stop) {
        Socket socket = null;
        try {
            index++;
            socket = serverSocket.accept(); // 主线程获取客户端连接
            LOGGER.debug("[MockServer]第" + index + "个客户端成功连接!");
            FdfsMockHandler handler = new FdfsMockHandler(socket);
            pool.put("第" + index + "个", handler);
            handler.start(); // 启动线程
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example 7
Source File: Socks5Proxy.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    while (true) {
        ServerSocket serverSocket = Socks5Proxy.this.serverSocket;
        if (serverSocket == null || serverSocket.isClosed() || Thread.currentThread().isInterrupted()) {
            return;
        }

        // accept connection
        Socket socket = null;
        try {
            socket = serverSocket.accept();
            // initialize connection
            establishConnection(socket);
        } catch (SmackException | IOException e) {
            // Do nothing, if caused by closing the server socket, thread will terminate in next loop.
            LOGGER.log(Level.FINE, "Exception while " + Socks5Proxy.this + " was handling connection", e);
            CloseableUtil.maybeClose(socket, LOGGER);
        }
    }
}
 
Example 8
Source File: SelectFdsLimit.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String [] args) throws IOException, FileNotFoundException {

        //The bug 8021820 is a Mac specific and because of that test will pass on all
        //other platforms
        if (!System.getProperty("os.name").contains("OS X")) {
           return;
        }

        //Create test directory with test files
        prepareTestEnv();

        //Consume FD ids for this java process to overflow the 1024
        openFiles(FDTOOPEN,new File(TESTFILE));

        //Wait for incoming connection and make the select() used in java.net
        //classes fail the limitation on FDSET_SIZE
        ServerSocket socket = new ServerSocket(0);

        //Set the minimal timeout, no one is
        //going to connect to this server socket
        socket.setSoTimeout(1);

        // The accept() call will throw SocketException if the
        // select() has failed due to limitation on fds size,
        // indicating test failure. A SocketTimeoutException
        // is expected, so it is caught and ignored, and the test
        // passes.
        try {
           socket.accept();
        } catch (SocketTimeoutException e) { }
    }
 
Example 9
Source File: SocketServer.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public
static void main(final String[] argv) {
   if (argv.length == 3) {
      init(argv[0], argv[1], argv[2]);
   } else {
      usage("Wrong number of arguments.");
   }

   try {
      cat.info("Listening on port " + port);
      final ServerSocket serverSocket = new ServerSocket(port);
      //noinspection InfiniteLoopStatement
      while (true) {
         cat.info("Waiting to accept a new client.");
         final Socket socket = serverSocket.accept();
         final InetAddress inetAddress = socket.getInetAddress();
         cat.info("Connected to client at " + inetAddress);

         LoggerRepository h = (LoggerRepository) server.hierarchyMap.get(inetAddress);
         if (h == null) {
            h = server.configureHierarchy(inetAddress);
         }

         cat.info("Starting new socket node.");
         new Thread(new SocketNode(socket, h)).start();
      }
   }
   catch (final Exception e) {
      e.printStackTrace();
   }
}
 
Example 10
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 11
Source File: GemFireMemcachedServer.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private void startMemcachedServer() throws IOException, InterruptedException {
  ServerSocketChannel channel = ServerSocketChannel.open();
  final ServerSocket serverSocket = channel.socket();
  serverSocket.bind(new InetSocketAddress(SocketCreator.getLocalHost(), serverPort));
  final CountDownLatch latch = new CountDownLatch(1);
  acceptor = new Thread(new Runnable() {
    public void run() {
      for (;;) {
        Socket s = null;
        try {
          latch.countDown();
          s = serverSocket.accept();
          handleNewClient(s);
        } catch (ClosedByInterruptException e) {
          try {
            serverSocket.close();
          } catch (IOException e1) {
            e1.printStackTrace();
          }
          break;
        } catch (IOException e) {
          e.printStackTrace();
          break;
        }
      }
    }
  }, "AcceptorThread");
  acceptor.setDaemon(true);
  acceptor.start();
  latch.await();
  logger.config("GemFireMemcachedServer server started on host:"+SocketCreator.getLocalHost()+" port: "+this.serverPort);
}
 
Example 12
Source File: Socks5Handler.java    From sockslib with Apache License 2.0 5 votes vote down vote up
@Override
public void doBind(Session session, CommandMessage commandMessage) throws SocksException,
    IOException {

  ServerSocket serverSocket = new ServerSocket(commandMessage.getPort());
  int bindPort = serverSocket.getLocalPort();
  Socket socket = null;
  logger.info("Create TCP server bind at {} for session[{}]", serverSocket
      .getLocalSocketAddress(), session.getId());
  session.write(new CommandResponseMessage(VERSION, ServerReply.SUCCEEDED, serverSocket
      .getInetAddress(), bindPort));

  socket = serverSocket.accept();
  session.write(new CommandResponseMessage(VERSION, ServerReply.SUCCEEDED, socket
      .getLocalAddress(), socket.getLocalPort()));

  Pipe pipe = new SocketPipe(session.getSocket(), socket);
  pipe.setBufferSize(bufferSize);
  pipe.start();

  // wait for pipe exit.
  while (pipe.isRunning()) {
    try {
      Thread.sleep(idleTime);
    } catch (InterruptedException e) {
      pipe.stop();
      session.close();
      logger.info("Session[{}] closed", session.getId());
    }
  }
  serverSocket.close();
  // throw new NotImplementException("Not implement BIND command");
}
 
Example 13
Source File: PizzaHut.java    From cs601 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void startAnsweringPhone() throws IOException {
	ServerSocket phone = new ServerSocket(PIZZA_HUT_PHONE_NUMBER);
	while (openForBusiness) {
		DataInputStream din = null;
		PrintStream pout = null;
		Socket phoneCall = null;
		try {
			// wait for a call; sleep while you are waiting
			phoneCall = phone.accept();
			// get an input stream (the headset speaker)
			InputStream in = phoneCall.getInputStream();
			din = new DataInputStream(in);
			// get an output stream (the microphone)
			OutputStream out = phoneCall.getOutputStream();
			pout = new PrintStream(out);

			// say hello
			pout.println("hello, Pizza Hut, how may I help you?");
			// take the order
			String order = din.readLine();
			// read it back to customer
			pout.println("your order: "+order); 

			createPizza(order);
		}
		finally {
			din.close();
			pout.close();
			phoneCall.close();
		}
	}
}
 
Example 14
Source File: Application.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    // bind to a random port
    if (args.length < 1) {
        System.err.println("First argument should be path to output file.");
    }
    String outFileName = args[0];

    ServerSocket ss = new ServerSocket(0);
    int port = ss.getLocalPort();
    int pid = ProcessTools.getProcessId();

    System.out.println("shutdownPort=" + port);
    System.out.println("pid=" + pid);
    System.out.flush();

    try (PrintWriter writer = new PrintWriter(outFileName)) {
        writer.println("shutdownPort=" + port);
        writer.println("pid=" + pid);
        writer.println("done");
        writer.flush();
    }

    // wait for test harness to connect
    Socket s = ss.accept();
    s.close();
    ss.close();
}
 
Example 15
Source File: SocketServer.java    From WiFi-and-Sensors-Indoor-Positioning with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) {

    try {
        serverSocket = new ServerSocket(8080);  //Server socket

    } catch (IOException e) {
        System.out.println("Could not listen on port: 8080");
    }

    System.out.println("Server started. Listening to the port 8080");

    while (true) {
        try {

            clientSocket = serverSocket.accept();   //accept the client connection
            inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
            bufferedReader = new BufferedReader(inputStreamReader); //get client msg                    
            message = bufferedReader.readLine();
            
            processMessage();
            
            inputStreamReader.close();
            clientSocket.close();
            
        } catch (IOException ex) {
            System.out.println("Problem in message reading");
        }
    }
    }
 
Example 16
Source File: BalancedParentheses.java    From openjdk-jdk8u-backup 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 17
Source File: NanoHTTPD.java    From DeviceConnect-Android with MIT License 4 votes vote down vote up
/**
 * Start the server.
 *
 * @throws IOException if the socket is in use.
 */
public void start() throws IOException {
    myServerSocket = new ServerSocket();
    myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));

    myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            do {
                try {
                    final Socket finalAccept = myServerSocket.accept();
                    registerConnection(finalAccept);
                    finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
                    final InputStream inputStream = finalAccept.getInputStream();
                    asyncRunner.exec(new Runnable() {
                        @Override
                        public void run() {
                            OutputStream outputStream = null;
                            try {
                                outputStream = finalAccept.getOutputStream();
                                TempFileManager tempFileManager = tempFileManagerFactory.create();
                                HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept.getInetAddress());
                                while (!finalAccept.isClosed()) {
                                    session.execute();
                                }
                            } catch (Exception e) {
                                // When the socket is closed by the client, we throw our own SocketException
                                // to break the  "keep alive" loop above.
                                if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) {
                                    e.printStackTrace();
                                }
                            } finally {
                                safeClose(outputStream);
                                safeClose(inputStream);
                                safeClose(finalAccept);
                                unRegisterConnection(finalAccept);
                            }
                        }
                    });
                } catch (IOException e) {
                }
            } while (!myServerSocket.isClosed());
        }
    });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
}
 
Example 18
Source File: HttpServer.java    From tutorial with MIT License 4 votes vote down vote up
public static void main(String[] argv) throws Exception {
    int port = 8090;
    ServerSocket serverSocket = new ServerSocket(port);

    while (true) {
        System.err.println("等待客户端接入... ...");
        Socket client = serverSocket.accept();
        System.err.println("有客户端接入 " + client.getInetAddress().getHostAddress());

        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);

        String action = in.readLine();
        if(action == null) {
            break;
        }
        System.out.println("客户端action: " + action);
        StringBuffer clientHeaders = new StringBuffer();
        for (String s = in.readLine(); s != null && s.length() > 0; s = in.readLine()) {
            clientHeaders.append(s);
            clientHeaders.append("\r\n");
        }
        System.out.println("客户端发送的Http Headers:\r\n" + clientHeaders);
        if (action.startsWith("GET ")) {
            // ok
            String html = "<!DOCTYPE html>\r\n" + "<html><head><title>hello,world</title>"
                    + "<body><h1>Hello, World!</h1><form method='POST'><input type='submit'></form></body></html>";
            out.print("HTTP/1.1 200 OK\r\n");
            // out.print("Date:" + new Date().toGMTString() + "\r\n");
            out.print("Context-Type: text/html\r\n");
            out.print("Content-Length:" + html.length() + "\r\n");
            out.print("Connection:close\r\n");
            out.print("\r\n");
            out.print(html);
        } else {
            out.print("HTTP/1.1 405 METHOD NOT ALLOWED\r\n");
            out.print("Connection:close\r\n");
            out.print("\r\n");
            out.print("方法 (" + action + ") 不允许。\r\n");
        }
        out.close();
        in.close();
        client.close();
    }
}
 
Example 19
Source File: WireMonitor.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
public void run() {
    try {
        // creating a server socket
        providerSocket = new ServerSocket(port, 10);

        log.info("WireMonitor Server started on port " + port);
        log.info("Waiting for connection");
        started = true;
        connection = providerSocket.accept();
        log.info("Connection received from " + connection.getInetAddress().getHostName());
        InputStream in = connection.getInputStream();
        int ch;
        StringBuffer buffer = new StringBuffer();
        StringBuffer headerBuffer = new StringBuffer();
        Long time = System.currentTimeMillis();
        int contentLength = -1;
        log.info("Reading message........");
        while ((ch = in.read()) != 1) {
            buffer.append((char) ch);
            //message headers end with
            if (contentLength == -1 && buffer.toString().endsWith("\r\n\r\n")) {
                headerBuffer = new StringBuffer(buffer.toString());
                if (buffer.toString().contains("Content-Length")) {
                    String headers = buffer.toString();
                    //getting content-length header
                    String contentLengthHeader = headers.substring(headers.indexOf("Content-Length:"));
                    contentLengthHeader = contentLengthHeader.substring(0, contentLengthHeader.indexOf("\r\n"));
                    contentLength = Integer.parseInt(contentLengthHeader.split(":")[1].trim());
                    //clear the buffer
                    buffer.setLength(0);
                }
            }

            //braking loop since whole message is red
            if (buffer.toString().length() == contentLength) {
                break;
            }
            // In this case no need of reading more than timeout value
            if (System.currentTimeMillis() > (time + TIMEOUT_VALUE) || buffer.toString()
                    .contains("</soapenv:Envelope>")) {
                break;
            }
        }
        log.info("Message received");
        // Signaling Main thread to continue
        trigger.response = headerBuffer.toString() + buffer.toString();
        OutputStream out = connection.getOutputStream();
        out.write(("HTTP/1.1 202 Accepted" + "\r\n\r\n").getBytes());
        out.flush();
        log.info("Ack sent");
        out.close();
        in.close();

    } catch (IOException ioException) {
        log.warn(ioException.getMessage());
    } finally {
        try {
            connection.close();
            providerSocket.close();
            log.info("Connection closed ");
        } catch (Exception e) {
            log.warn(e.getMessage());
        }
    }
    trigger.isFinished = true;

}
 
Example 20
Source File: NanoHTTPD.java    From jmeter-plugins with Apache License 2.0 4 votes vote down vote up
/**
 * Start the server.
 *
 * @throws IOException
 *             if the socket is in use.
 */
public void start() throws IOException {
    myServerSocket = new ServerSocket();
    myServerSocket.bind((hostname != null) ? new InetSocketAddress(
            hostname, myPort) : new InetSocketAddress(myPort));

    myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            do {
                try {
                    final Socket finalAccept = myServerSocket.accept();
                    registerConnection(finalAccept);
                    finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
                    final InputStream inputStream = finalAccept
                            .getInputStream();
                    asyncRunner.exec(new Runnable() {
                        @Override
                        public void run() {
                            OutputStream outputStream = null;
                            try {
                                outputStream = finalAccept
                                        .getOutputStream();
                                TempFileManager tempFileManager = tempFileManagerFactory
                                        .create();
                                HTTPSession session = new HTTPSession(
                                        tempFileManager, inputStream,
                                        outputStream, finalAccept
                                                .getInetAddress());
                                while (!finalAccept.isClosed()) {
                                    session.execute();
                                }
                            } catch (Exception e) {
                                // When the socket is closed by the client,
                                // we throw our own SocketException
                                // to break the "keep alive" loop above.
                                if (!(e instanceof SocketException && "NanoHttpd Shutdown"
                                        .equals(e.getMessage()))) {
                                    e.printStackTrace();
                                }
                            } finally {
                                safeClose(outputStream);
                                safeClose(inputStream);
                                safeClose(finalAccept);
                                unRegisterConnection(finalAccept);
                            }
                        }
                    });
                } catch (IOException e) {
                }
            } while (!myServerSocket.isClosed());
        }
    });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
}