简体   繁体   中英

about the returned Socket object from SocketServer

I have a very simple question, however I am confused by a tutorial.

Say, I create a server & use port 1234:

ServerSocket server = new ServerSocket(1234);

Then, I ask server to wait for requests by:

while(true) {
  // is the returned socket represents the server side socket or client side socket???
  Socket socket = server.accept();
}

My question is whether the socket returned by server.accept() a server side socket or client side socket? It is not very well explained in Java doc .

The reason why I ask this question is because when I run socket.getPort() , it doesn't return server port 1234, instead, it returns a port not defined by me, so, I am thinking it might be the client's socket. But I am not sure.

Listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made.

which means, that it is server.

socket.getPort() according to javadoc ,

Returns the remote port number to which this socket is connected.

A Socket has two ends, where one end will send information to the other end with the OutputStream, and receive information from the other end with the InputStream. See also getInputStream() and getOutputStream() methods on the Socket.

In your terms, you can consider the socket to be server side because the InputStream is receiving information from the client that has connected to the server, and the OutputStream is sending information to the client.

Typically once the socket is obtained with the server.accept() method, a thread, created with the socket you obtained, should be used for communicating with the client, so that your server can handle multiple clients at the same time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM