Is new socket created for every request?

2020-06-18 09:22发布

问题:

I am trying to wrap my head around network sockets. So far my understanding is that a server creates a new socket that is bound to the specific port. Then it listens to this socket to deal with client requests.

I've read this tutorial http://docs.oracle.com/javase/tutorial/networking/sockets/definition.html and it says

If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client. It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client.

Here are a few things that I don't quite understand

If everything goes well, the server accepts the connection.

  1. Does it mean that a client request successfully arrived at the listening socket?

Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client

  1. The new socket is created. It also gets bound to the same port but it doesn't listen for incoming requests. After server processed client request resonse is written to this socket and then it gets closed. Is it correct?

  2. Does it mean that request is somehow passed from the first socket to the second socket?

It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client.

  1. So, the new socket is created then that listens for incoming request. Are there different type of sockets? Some kind of "listening" sockets and other?

  2. Why does the server have to create a new listening socket? Why can't it reuse the previous one?

回答1:

  1. No. It means that an incoming connection arrived at the server.
  2. No. It gets closed if the server closes it. Not otherwise.
  3. No. It means that the incoming connection causes a connection to be fully formed and a socket created at the server to represent the server-end endpoint of it.
  4. (a) No. A new socket is created to receive requests and send responses. (b) Yes. There are passive and active sockets. A passive socket listens for connections. An active socket sends and receives data.
  5. It doesn't have to create a new listening (passive) socket. It has to create a new active socket to be the endpoint of the new connection.

Is new socket created for every request?

Most protocols, for example HTTP with keep-alive, allow multiple requests per connection.



回答2:

1) An incoming connection has arrived 2) Socket doesn't get closed 3) There is server socket and just socket. Server socket.accept returns a socket object when a client connects