Java server /port question
Hi All
I wrote this little bit of code to try and start learning about "servers"
package webserver;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
publicclass WebServer{
publicstaticvoid main(String[] args){
try{
ServerSocket server =new ServerSocket(0);
System.out.println("This server runs on port " + server.getLocalPort());
Socket s = server.accept();
System.out.println(s.getPort());
}catch (IOException ex){
System.err.println(ex);
}
}
}
System.out.print message back with a port number but I don't get any message back for the s.getPort in the second System.out request.
This I assume means the server.accept() isn't working.
Any ideas why?
I have Tomcat bundled with netbeans 5.5.
Why isn't the server accepting?
Cheers
Dan
Message was edited by:
DanielFoord
accept() blocks until it gets a connection. That is, it sits and waits until there is a connection, and then returns a socket describing that connection. Run your program, then telnet to localhost on the port you're listening on (don't use port '0'!), you'll see the second sysout print
server.accept blocks until someone (other process) tries to connect to the port that the server socket is accepting on.
After you start your server program, try to connect to it (to the server socket tha you created) with some client program like telnet or a web browser.
If you use telnet try 'telnet localhost <port_number>'.
If you use a web broser use http://localhost:<port_number>/
After client program connects, your server will return from the blocking server.accept call, and write the second println.
Thanks for that.
I had no luck with the telnet solution -
typed in at the Microsoft Telenet> prompt
telnet localhost3555
telnet localhost 3555
localhost3555
localhost 3555
but all returned invalid command (any ideas?).
However the browser option worked
2 questions -
The browser returned problem loading page - I assume that's because the "page" doesn't actually exist. I haven't coded a page!
Secondly the port returned by s.getport() (See original code) is different to that of the server.getLocalPort - what is the difference between the two?
Cheers
Dan
null