Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Socket connection  RSS feed

 
Akash Kumar
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All
I have a very small question regarding coocention:
What should be code to listens a socket connection?
Ans.
Socket socket = HttpURLConnection.open(8080);
or
Socket socket = SocketImpl.listen(8080);
or something else
Thanks in advance
Akash
 
Blake Minghelli
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmmm... HttpURLConnection.open() doesn't seem to exist
SocketImpl.listen() does not take a port as a parameter
If you are trying to create a "server" listening to a specific port, then here is a code snippet which may help:

Hope that hepls
 
Akash Kumar
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Blake !
So the command should be like this
Socket socket = (new ServerSocket(8080)).accept();
Thanks once again!
 
Blake Minghelli
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

So the command should be like this
Socket socket = (new ServerSocket(8080)).accept();

That code is structurally correct, but I wouldn't suggest constructing a new ServerSocket with every request like that. It would be more efficient to create the ServerSocket object just once.
Two important things to note:
1. You can't use the same port for more than one ServerSocket instance, otherwise you'll get an exception.
2. Once you get a socket (via .accept()), it's important that a separate thread handles the request. Otherwise, your server socket will not be able to accept any more requests until the current request is complete.
[ September 27, 2002: Message edited by: Blake Minghelli ]
[ September 27, 2002: Message edited by: Blake Minghelli ]
 
Akash Kumar
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the nice reply.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!