java.net.ServerSocket类的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(10.2k)|赞(0)|评价(0)|浏览(129)

本文整理了Java中java.net.ServerSocket类的一些代码示例,展示了ServerSocket类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ServerSocket类的具体详情如下:
包路径:java.net.ServerSocket
类名称:ServerSocket

ServerSocket介绍

[英]This class represents a server-side socket that waits for incoming client connections. A ServerSocket handles the requests and sends back an appropriate reply. The actual tasks that a server socket must accomplish are implemented by an internal SocketImpl instance.
[中]此类表示等待传入客户端连接的服务器端套接字。ServerSocket处理请求并返回适当的回复。服务器套接字必须完成的实际任务由内部SocketImpl实例实现。

代码示例

代码示例来源:origin: stackoverflow.com

ServerSocket serverSocket = new ServerSocket(4444);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
while (true) {
 out.println("output");
 if (out.checkError()) System.out.println("ERROR writing data to socket !!!");
 System.out.println(clientSocket.isConnected());
 System.out.println(clientSocket.getInputStream().read());
    // thread sleep ...
 // break condition , close sockets and the like ...
}

代码示例来源:origin: spring-projects/spring-framework

@Override
  protected boolean isPortAvailable(int port) {
    try {
      ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(
          port, 1, InetAddress.getByName("localhost"));
      serverSocket.close();
      return true;
    }
    catch (Exception ex) {
      return false;
    }
  }
},

代码示例来源:origin: kilim/kilim

ListenTask(int port) throws IOException {
  this.port = port;
  this.ssc = ServerSocketChannel.open();
  ssc.socket().setReuseAddress(true);
  ssc.socket().bind(new InetSocketAddress(port), LISTEN_BACKLOG);
  ssc.configureBlocking(false);
  endpoint = new EndPoint(NioSelectorScheduler.this,ssc);

  // if port is automatically assigned then retrieve actual value
  if(port == 0) {
    this.port = ssc.socket().getLocalPort();
  };    
}

代码示例来源:origin: apache/incubator-dubbo

public static int getAvailablePort() {
  try (ServerSocket ss = new ServerSocket()) {
    ss.bind(null);
    return ss.getLocalPort();
  } catch (IOException e) {
    return getRandomPort();
  }
}

代码示例来源:origin: Alluxio/alluxio

private static boolean isLocalPortAvailable(int port) {
  try (ServerSocket socket = new ServerSocket(port)) {
   socket.setReuseAddress(true);
   return true;
  } catch (IOException e) {
   return false;
  }
 }
}

代码示例来源:origin: go-lang-plugin-org/go-lang-idea-plugin

private static int findFreePort() {
  try(ServerSocket socket = new ServerSocket(0)) {
   socket.setReuseAddress(true);
   return socket.getLocalPort();
  }
  catch (Exception ignore) {
  }
  throw new IllegalStateException("Could not find a free TCP/IP port to start dlv");
 }
}

代码示例来源:origin: apache/incubator-druid

@Override
 public void run()
 {
  while (!Thread.currentThread().isInterrupted()) {
   try (
     Socket clientSocket = serverSocket.accept();
     BufferedReader in = new BufferedReader(
       new InputStreamReader(clientSocket.getInputStream(), StandardCharsets.UTF_8)
     );
     OutputStream out = clientSocket.getOutputStream()
   ) {
    while (!in.readLine().equals("")) {
     // skip lines
    }
    out.write("HTTP/1.1 200 OK\r\nContent-Length: 6\r\n\r\nhello!".getBytes(StandardCharsets.UTF_8));
   }
   catch (Exception e) {
    // Suppress
   }
  }
 }
}

代码示例来源:origin: normanmaurer/netty-in-action

/**
 * Listing 1.1 Blocking I/O example
 * */
public void serve(int portNumber) throws IOException {
  ServerSocket serverSocket = new ServerSocket(portNumber);
  Socket clientSocket = serverSocket.accept();
  BufferedReader in = new BufferedReader(
      new InputStreamReader(clientSocket.getInputStream()));
  PrintWriter out =
      new PrintWriter(clientSocket.getOutputStream(), true);
  String request, response;
  while ((request = in.readLine()) != null) {
    if ("Done".equals(request)) {
      break;
    }
    response = processRequest(request);
    out.println(response);
  }
}

代码示例来源:origin: stackoverflow.com

serverSocket = new ServerSocket(2005);
connect();
socket = serverSocket.accept();
System.out.println("Got connection");
if(handshake()) {
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (!(str = in.readLine()).equals("")) {
  String[] s = str.split(": ");
  System.out.println();
out.write("HTTP/1.1 101 Switching Protocols\r\n"
  + "Upgrade: websocket\r\n"
  + "Connection: Upgrade\r\n"
  + "Sec-WebSocket-Accept: " + hash + "\r\n"
  + "\r\n");
out.flush();
socket.getInputStream().read(b);
return b;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
  System.out.println("Write something to the client!");

代码示例来源:origin: igniterealtime/Openfire

if (interfaceName != null) {
  if (interfaceName.trim().length() > 0) {
    bindInterface = InetAddress.getByName(interfaceName);
serverSocket = new ServerSocket(port, -1, bindInterface);
Log.debug("Flash cross domain is listening on " + interfaceName + " on port " + port);
BufferedReader in = null;
try {
  clientSocket = serverSocket.accept();
  clientSocket.setSoTimeout(10000); // 10 second timeout
  out = new PrintWriter(clientSocket.getOutputStream(), true);
  in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    out.write(CROSS_DOMAIN_TEXT +
        XMPPServer.getInstance().getConnectionManager().getClientListenerPort() +
        CROSS_DOMAIN_END_TEXT+"\u0000");
    out.flush();
    out.close();
    in.close();

代码示例来源:origin: apache/flink

@Test
public void testSocketSink() throws Exception {
  final ServerSocket server = new ServerSocket(0);
  final int port = server.getLocalPort();
  Socket sk = server.accept();
  BufferedReader rdr = new BufferedReader(new InputStreamReader(sk.getInputStream()));
  String value = rdr.readLine();
  server.close();

代码示例来源:origin: jmxtrans/jmxtrans

private void processRequests(ServerSocket server) throws IOException {
  Socket socket = server.accept();
  connectionsAccepted.incrementAndGet();
  try (
      BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), UTF_8));
      PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), UTF_8))
  ){
    synchronized (startSynchro) {
      startSynchro.notifyAll();
    }
    String line;
    while ((line = in.readLine()) != null) {
      receivedMessages.add(line);
      out.print(line);
    }
  }
}

代码示例来源:origin: org.apache.logging.log4j/log4j-core

client = null;
try {
  server = new ServerSocket(SOCKET_PORT);
  client = server.accept();
  while (!shutdown) {
    final BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
    final String line = reader.readLine();
    if (line.equals("Shutdown")) {
      shutdown = true;
  if (client != null) {
    try {
      client.close();
    } catch (final Exception ex) {
      System.out.println("Unable to close socket " + ex.getMessage());
      server.close();
    } catch (final Exception ex) {
      System.out.println("Unable to close server socket " + ex.getMessage());

代码示例来源:origin: apache/flink

@Override
  public Void call() throws Exception {
    Socket socket = serverSocket[0].accept();
    BufferedReader reader = new BufferedReader(new InputStreamReader(
        socket.getInputStream()));
    String value = reader.readLine();
    assertEquals("0", value);
    socket.close();
    return null;
  }
};

代码示例来源:origin: org.apache.logging.log4j/log4j-core

try {
  try {
    serverSocket = new ServerSocket(port);
    serverSocket.setSoTimeout(TIMEOUT); // Block for maximum of 1.5 seconds
  } finally {
    synchronized (this) {
      socket = serverSocket.accept();
    } catch (final Exception e) {
      if (socket != null) {
        socket.close();
    final BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    final PrintWriter out = new PrintWriter(socket.getOutputStream());
  if (serverSocket != null) {
    try {
      serverSocket.close();
    } catch (final IOException e) {
      e.printStackTrace();

代码示例来源:origin: AsyncHttpClient/async-http-client

@BeforeClass
public void setUpGlobal() throws Exception {
 serverSocket = ServerSocketFactory.getDefault().createServerSocket(0);
 port1 = serverSocket.getLocalPort();
 executorService = Executors.newFixedThreadPool(1);
 voidFuture = executorService.submit(() -> {
   Socket socket;
   while ((socket = serverSocket.accept()) != null) {
    InputStream inputStream = socket.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    String req = reader.readLine().split(" ")[1];
    int i = inputStream.available();
    long l = inputStream.skip(i);
    assertEquals(l, i);
    socket.shutdownInput();
    if (req.endsWith("MultiEnt")) {
     OutputStreamWriter outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
     outputStreamWriter.append("HTTP/1.0 200 OK\n" + "Connection: close\n" + "Content-Type: text/plain; charset=iso-8859-1\n" + "Content-Length: 2\n"
         + "Content-Length: 1\n" + "\n0\n");

代码示例来源:origin: stackoverflow.com

serverSocket = new ServerSocket(4444);
} catch (IOException ex) {
  System.out.println("Can't setup server on this port number. ");
  socket = serverSocket.accept();
} catch (IOException ex) {
  System.out.println("Can't accept client connection. ");
  in = socket.getInputStream();
} catch (IOException ex) {
  System.out.println("Can't get socket input stream. ");
  out.write(bytes, 0, count);
out.close();
in.close();
socket.close();
serverSocket.close();

代码示例来源:origin: apache/flink

public boolean preparePlanMode() throws IOException {
  try {
    process.getOutputStream().write((server.getLocalPort() + "\n").getBytes(ConfigConstants.DEFAULT_CHARSET));
    process.getOutputStream().flush();
  } catch (IOException ignored) {
    // the python process most likely shutdown in the meantime
    return false;
  }
  while (true) {
    try {
      socket = server.accept();
      sender = new PythonPlanSender(socket.getOutputStream());
      receiver = new PythonPlanReceiver(socket.getInputStream());
      return true;
    } catch (SocketTimeoutException ignored) {
      switch(checkPythonProcessHealth()) {
        case RUNNING:
          continue;
        case STOPPED:
          return false;
        case FAILED:
          throw new RuntimeException("Plan file caused an error. Check log-files for details.");
      }
    }
  }
}

代码示例来源:origin: log4j/log4j

while(!serverSocket.isClosed()) {
 try {
  Socket newClient = serverSocket.accept();
  PrintWriter pw = new PrintWriter(newClient.getOutputStream());
  if(connections.size() < MAX_CONNECTIONS) {
   synchronized(this) {
     connections.addElement(newClient);
     writers.addElement(pw);
     pw.print("TelnetAppender v1.0 (" + connections.size()
       + " active connections)\r\n\r\n");
     pw.flush();
   pw.print("Too many connections.\r\n");
   pw.flush();
   newClient.close();
    Thread.currentThread().interrupt();
  if (!serverSocket.isClosed()) {
   LogLog.error("Encountered error while in SocketHandler loop.", e);
  serverSocket.close();
} catch(InterruptedIOException ex) {
  Thread.currentThread().interrupt();

代码示例来源:origin: stackoverflow.com

String s = tf.getText();
if (out != null) {
  out.println(s);
  Socket socket;
  if (kind == Kind.Client) {
    socket = new Socket(HOST, PORT);
  } else {
    ServerSocket ss = new ServerSocket(PORT);
    socket = ss.accept();
  in = new Scanner(socket.getInputStream());
  out = new PrintWriter(socket.getOutputStream(), true);
  display("Connected");
  while (true) {

相关文章