• Post Reply Bookmark Topic Watch Topic
  • New Topic

ServerSocket's accept()  RSS feed

 
Manny Hernandez
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

I've come across this code in the Head First Java 2nd edition book
where I need to shed some light on. First, please see the code
snippet below from page 521:




--------------------------
Now, the question. Since there's a while loop in this method
that's running infinitely, shouldn't this print the "got a connection"
string infinitely? When you complete the program, you'll
see that this isn't the case. So I'm thinking that the
whole while loop stops at this point in the code before proceeding:

Socket clientSocket = serverSock.accept();

So is the accept() method running its own infinite loop? (one
that returns the control to the calling method only if there is
a value that's been provided?) Is it safe to say that this
accept() method has some infinite iteration that does the following:

while( accept == null ) {
//code for assigning value to null
//return SocketObject
}
 
Paul Clapham
Sheriff
Posts: 22831
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The accept() method waits until it receives a connection from a client. Yes, it can wait forever if it no clients ever try to connect to it.
 
Manny Hernandez
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, I understand, but just to be clear, the rest of the code
in the method doesn't run UNTIL a connection is received,
correct?
 
Paul Clapham
Sheriff
Posts: 22831
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's right. Nothing happens until the accept() method returns. That's how method calls work in Java.
 
Manny Hernandez
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, Paul!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!