java.net.ServerSocket.accept()方法的使用及代码示例

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

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

ServerSocket.accept介绍

[英]Waits for an incoming request and blocks until the connection is opened. This method returns a socket object representing the just opened connection.
[中]等待传入请求并阻塞,直到连接打开。此方法返回一个表示刚刚打开的连接的套接字对象。

代码示例

代码示例来源: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: stackoverflow.com

public class ThreadedEchoServer {

  static final int PORT = 1978;

  public static void main(String args[]) {
    ServerSocket serverSocket = null;
    Socket socket = null;

    try {
      serverSocket = new ServerSocket(PORT);
    } catch (IOException e) {
      e.printStackTrace();

    }
    while (true) {
      try {
        socket = serverSocket.accept();
      } catch (IOException e) {
        System.out.println("I/O error: " + e);
      }
      // new threa for a client
      new EchoThread(socket).start();
    }
  }
}

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

/**
 * Main server loop.
 */
@Override
public void run() {
  try {
    mServer = new ServerSocket(mPort, VIEW_SERVER_MAX_CONNECTIONS, InetAddress.getLocalHost());
  } catch (Exception e) {
    Log.w(LOG_TAG, "Starting ServerSocket error: ", e);
  }
  while (mServer != null && Thread.currentThread() == mThread) {
    // Any uncaught exception will crash the system process
    try {
      Socket client = mServer.accept();
      if (mThreadPool != null) {
        mThreadPool.submit(new ViewServerWorker(client));
      } else {
        try {
          client.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    } catch (Exception e) {
      Log.w(LOG_TAG, "Connection error: ", e);
    }
  }
}

代码示例来源:origin: square/okio

private void acceptSockets() {
 try {
  while (true) {
   final Socket from = serverSocket.accept();
   openSockets.add(from);
   executor.execute(() -> handleSocket(from));
  }
 } catch (IOException e) {
  System.out.println("shutting down: " + e);
 } finally {
  for (Socket socket : openSockets) {
   closeQuietly(socket);
  }
 }
}

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

public class DoSomethingWithInput implements Runnable {
  private final Socket clientSocket; //initialize in const'r
  public void run() {

    BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    String nextline;
    while ((nextline = in.readLine())!=null) {
      System.out.println(nextline);
    } //... close socket, etc.
  }
}

//...
ServerSocket serverSocket = null;
serverSocket = new ServerSocket(5432);
for (;;) {
  Socket clientSocket = null;
  clientSocket = serverSocket.accept();
  //delegate to new thread
  new Thread(new DoSomethingWithInput(clientSocket)).start();
} //...

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

public class MyServer {
  public static final int PORT = 12345;
  public static void main(String[] args) throws IOException, InterruptedException {
    ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);
    Socket s = ss.accept();
    Thread.sleep(5000);
    ss.close();
    s.close();
  }
}

public class MyClient {
  public static void main(String[] args) throws IOException, InterruptedException {
    Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT);
    System.out.println(" connected: " + s.isConnected());
    Thread.sleep(10000);
    System.out.println(" connected: " + s.isConnected());
  }
}

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

if (listener != null) listener.onDisconnected();
System.out.println("listening, port " + port);
Socket socket = null;
socket = serverSocket.accept();
socket.setTcpNoDelay(true);
socket.setSoTimeout(3000);
if (listener != null) listener.onConnected();
DataInputStream in = new DataInputStream(socket.getInputStream());
multiTouch = in.readBoolean();
while (true) {

代码示例来源: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: Netflix/servo

@Override
public void run() {
 while (running) {
  try {
   s = acceptor.accept();
   synchronized (this) {
    connected = true;
    notify();
   }
   BufferedReader stream = new BufferedReader(
     new InputStreamReader(s.getInputStream(), "UTF-8"));
   while (running) {
    String line = stream.readLine();
    synchronized (this) {
     lines[linesWritten++ % lines.length] = line;
     notify();
    }
   }
  } catch (IOException e) {
   synchronized (this) {
    connected = false;
    linesWritten = 0;
    linesRead = 0;
    notify();
   }
  }
 }
}

代码示例来源: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: plantuml/plantuml

public static void main(String args[]) throws Exception {
  final ServerSocket server = new ServerSocket(4242);
  while (true) {
    final Socket socket = server.accept();
    new AcceptTelnetClient(socket);
  }
}

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

@Override
public InputStream call() throws Exception {
  server = new ServerSocket(SOCKET_PORT);
  client = server.accept();
  return client.getInputStream();
}

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

while(!serverSocket.isClosed()) {
 try {
  Socket newClient = serverSocket.accept();
  PrintWriter pw = new PrintWriter(newClient.getOutputStream());
  if(connections.size() < MAX_CONNECTIONS) {
   synchronized(this) {
   pw.print("Too many connections.\r\n");
   pw.flush();
   newClient.close();

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

private T readNextFromStream() throws Exception {
  try {
    if (inStream == null) {
      connectedSocket = socket.accept();
      inStream = new DataInputViewStreamWrapper(connectedSocket.getInputStream());
    }
    return serializer.deserialize(inStream);
  }
  catch (EOFException e) {
    try {
      connectedSocket.close();
    } catch (Throwable ignored) {}
    try {
      socket.close();
    } catch (Throwable ignored) {}
    return null;
  }
  catch (Exception e) {
    if (error == null) {
      throw e;
    }
    else {
      // throw the root cause error
      throw new Exception("Receiving stream failed: " + error.getMessage(), error);
    }
  }
}

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

@Override
public InputStream call() throws Exception {
  client = server.accept();
  return client.getInputStream();
}

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

@Override
public void run() {
  try {
    try (Socket socket = serverSocket.accept();
        PrintWriter writer = new PrintWriter(socket.getOutputStream(), true)) {
      writer.println(WordCountData.TEXT);
    }
  }
  catch (Throwable t) {
    this.error = t;
  }
}

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

String msg_received;

ServerSocket socket = new ServerSocket(1755);
Socket clientSocket = socket.accept();       //This is blocking. It will wait.
DataInputStream DIS = new DataInputStream(clientSocket.getInputStream());
msg_received = DIS.readUTF();
clientSocket.close();
socket.close();

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

public void go() throws IOException {
  final ServerSocket s = new ServerSocket(listenPort);
  final ExecutorService exe = Executors.newCachedThreadPool();
  while (true) {
    final Socket incoming = s.accept();
    ip = incoming.getLocalAddress().getHostAddress();
    System.out.println("New Client Connected from " + incoming.getInetAddress().getHostName() + "... ");
    exe.submit(new FtpLoop(incoming, this));
  }
}

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

/**
 * Begins the HTTP service.
 */
public void run() {
  System.err.println("ready to service...");
  for (;;)
    try {
      ServiceThread th = new ServiceThread(this, socket.accept());
      th.start();
    }
    catch (IOException e) {
      logging(e.toString());
    }
}

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

if (listener != null) listener.onDisconnected();
System.out.println("listening, port " + port);
Socket socket = null;
socket = serverSocket.accept();
socket.setTcpNoDelay(true);
socket.setSoTimeout(3000);
if (listener != null) listener.onConnected();
DataInputStream in = new DataInputStream(socket.getInputStream());
multiTouch = in.readBoolean();
while (true) {

相关文章