zoukankan      html  css  js  c++  java
  • [Question]Question about "java.net.ServerSocket.accept()"

    Question:
    java.net.ServerSocket.accept() will listen to the specified port for some requests and create a socket.

    But some question bewilder me.

    There is a code :

    ServerSocket serverSocket = new ServerSocket(listenPort);  // Create a server socket to listen to the sepcified port.
          while(true) {  // Keep listening without break.
            Socket incomingConnection = serverSocket.accept();
            handleConnection(incomingConnection);  // Handle the request with multi thread.
          }
        } catch (BindException e) {
            System.out.println("Unable to bind to port " + listenPort);
        } catch (IOException e) {
            System.out.println("Unable to instantiate a ServerSocket on port: " + listenPort);
        }
    


    The while {} block make the ServerSocket keep listening every time. If there is a request, the accept() method will create a socket and will not be block until a connection is made.

    But ,if there are more than one request at the same time? What will the accept() method process? Will it create sockets for each request at the same time?

    Answer:
    > But ,if there are more than one request at the same
    > time? What will the accept() method process?

    Two network packets don't arrive at the same time on the network card, so there can't be exactly simultaneous connections. (Well, ok, unless you have two network cards and two CPUs...)

    If there are two requests very close to each other, accept() returns one, then the other on the next call.

    accept() will queue requests upto some limit - google for "TCP connection backlog". There is also some backlog stuff in ServerSocket, look at the API. Usually you don't need to worry about it, the default backlog is fine.

    And, as PL says, immediately after accept() returns, fire off a new thread to handle the request. That way your accepting thread can get right back into calling accept(). Then the backlog won't overflow - your CPU is much faster doing accept() than the network card is at receiving new connections.
  • 相关阅读:
    所有问题都可以通过增加一层来解决
    open一个页面并关闭父页(小技巧)
    <%=字符串%>回刷技巧(小技巧)
    轮环(Ouroboros)世界观介绍,摘自Guide Book
    windows7下MSN如何最小化到任务栏
    触发器权限
    网页GZIP压缩
    iis6配置使用页面Gzip压缩提速
    唉,被删的帖
    创建型模式,结构型模式,结构型模式
  • 原文地址:https://www.cnblogs.com/johnny/p/170729.html
Copyright © 2011-2022 走看看