ServerSocket problem, please help
Hi,
I have written a java program which will create a ServerSocket object at a port. For example:
ServerSocket serverSocket = new ServerSocket(port);
Then I create a socket to accept connection from this port. If a connection is detected, a method will be called and once it is finished, the socket will be closed.
The problem is that my program will then create another ServerSocket at the same port. However this doesn't work. What I believe is that although the socket that was created at the beginning has been closed, the port is still being used or "being held" so that the second time I tried to create another ServerSocket at the same port, it didn't work.
Therefore I would like to ask how I can use a port (ie. create a new ServerSocket object) which has been used in the same program.
The bottom line is I must have to create a new ServerSocket object each time when I need to use that port.
Thank you very much.
Best regards,
Jackie
I assume we're talking about java.net.ServerSocket (not nio).
ServerSocket.accept returns a Socket, on a different port, which can be used to communicate. The ServerSocket continues to listen to the port you originally asked it to listen to. To get a second connection, call ServerSocker.accept AGAIN. It will return yet another Socket, on a different port, to handle the second connection.
Use ServerSocket.accept() in a loop to continue handling the new connections.
> I must have to create a new ServerSocket object each time when I need to use that port.As another reply suggests, you must not do it.
hiwaa at 2007-7-13 3:27:58 >

Congratulations me on getting to answer this question for the 1 millionth time. Please pay attention class.
A Socket is uniquely identified by 4 (four) pieces of information. That's right 4. This is an important because this is the most popular misconception common to those who ask about multiple connections to the same server port.
So what are these four pieces of information? One is the local IP. Two is the local port. Three is the remote IP. Four is the remote port.
Now when I use the terms remote and local here it is important to note the following. When you get a socket from ServerSocket accept it is a Socket and nothing more. So you can view the terms local and remote interchangably and get the same results. By this I mean from one side of the connection the local stuff is the local stuff and the remote is the remote and the information is inverted for the other side of the connection. What was remote is now the local side and what was the local is now the remote.
Bottom line. There four pieces of information that TOGETHER make up a unique socket.
The piece of information that is pseudo random in all of this is the client's outgoing port. The client as in the machine making the REQUEST to the server socket.
When you request a new socket connection from the OS the OS automagically gives you a port number to use. One that is not already use on the system.
This is key because now you have unique piece of information a socket on port not used by any other with an IP (that is unique on it's network).
This means that since the socket on both sides has both the remote and local address information AND port numbers that the socket is unique for both sides.
Thus your server application may continue to use the port that you listen on to respond to client requests because the socket is actually unique to the OS and it knows this.
To make a very long story short do not worry about your port being in use with your ServerSocket. Each socket you get from accept will be unique and will not interfere with your ability to accept new connections (providing of course that you have multithreaded your server in such a way that you are able to return to accept without discarding the open socket) . If you understand this from this lengthy ramble then my congratulations however if you prefer to accept this fact as voodoo magic that's okay too.
hiwaa at 2007-7-13 3:27:59 >

Thanks for all your information. I guess I now have a better understanding of ServerSocket. Cheers.
Hi,
My program still doesn't work. So basically my program has a method as follow:
private ServerSocket serverSocket;
public void Connecting( )
{
.try
.{
.serverSocket = new ServerSocket(1234);
.}
.catch (Exception e) {}
.
.while (true)
.{
. try
. {
. Socket socket = serverSocket.accept();
. socket.close();
. break;
. }
. catch (Exception e) {System.out.println(e.getMessage( );}
.}
}
The first time I called this method, it worked fine. But the second time I called this method, it didn't work. An exception was caught and I got the message as follow:
Address already in use: JVM_Bind
Would you please advise how I can change the method so that each time I call this method and the serverSocket will be able to setup correctly (given that I want to use the same port again and again) ?
Thanks for your help.
Regards,
Jackie
It is highly unusual to create several ServerSockets like that. Instead, you should create one of them at the beginning of the program. Then call accept() for that same ServerSocket over and over again.
Google for "java socket tutorial". The first hit should be Sun's tutorial; there is a chapter "writing a client/server pair" with sample code that you can use as a boilerplate.
> But the second time I called this method, it didn't
> work. An exception was caught and I got the message
> as follow:
>
> Address already in use: JVM_Bind
That's absolutely correct. The second time you call this method you are asking a new ServerSocket to bind itself to 1234, and 1234 is still being watched by ServerSocket you created the FIRST time you called this method.
As long as you're posting this question twice in the same forum in as many days, let me continue...
Do this:serverSocket = new ServerSocket(1234);
serverSocket = new ServerSocket(1234);
You'll notice how the second line throws an exception telling you something's already bound to 1234.
ServerSocket gets bound to 1234 and just sits there, listening to it, watching, waiting, for any connections coming in on that port. Your code may go off and do other stuff, like walking the dog and washing your ******, but as long as the JVM is running and you haven't shut down that ServerSocket, it will sit there listening to 1234. All you have to do to handle additional connections on 1234 is repeatedly call serverSocket.accept(). Accept will return a Socket. That Socket's LOCAL port WILL BE DIFFERENT from the port number serverSocket is listening on. That's how it is designed to work! It's OK! Really, that's fine!
sjasja is right. You're lost.
Here is a VERY basic idea. In which each socket accepted causes a new handling thread to be spawned. This thread deals with the client connection and then dies. There are lost of alternatives to this.... like a queue of sockets and a pool of threads but whatever...
You can also have a single thread. But that will force you to only handle one connection at a time. Which doesn't appear to be what you want. But you don't keep creating ServerSockets. You create ONE. And then you keep calling accept()
public class Server{
public static void main(String args[]){
try{
ServerSocket ss = new ServerSocket(port);
while(somebooleansemaphore){
Socket s = ss.accept();
Thread t = new Thread(new ClientHandler(s));
t.start();
}
ss.close();
}catch(Exception e){
System.out.println("Whoops we died.");
e.printStackTrace();
}
}
public class ClientHandler implements Runnable{
private Socket s;
public ClientHandler(Socket s){
this.s = s;
}
public void run(){
//do stuff with the socket in here
s.close();
}
}
By ****** I was attempting to refer to the civillian version of the military HumVee. What's wrong with the word ******?!?! Shees!!!
> ServerSocket gets bound to 1234 and just sits there,
> listening to it, watching, waiting, for any
> connections coming in on that port. Your code may go
> off and do other stuff, like walking the dog and
> washing your ******, but as long as the JVM is
> running and you haven't shut down that ServerSocket,
> it will sit there listening to 1234. All you have to
> do to handle additional connections on 1234 is
> repeatedly call serverSocket.accept(). Accept will
> return a Socket. That Socket's LOCAL port WILL BE
> DIFFERENT from the port number serverSocket is
> listening on. That's how it is designed to work! It's
> OK! Really, that's fine!
No it won't. That sockets REMOTE port will be different for each connection. The remote address may be different as well. It really doesn't matter because each Socket will be unique. But the LOCAL port will be the same.
> By ****** I was attempting to refer to the civillian
> version of the military HumVee. What's wrong with the
> word ******?!?! Shees!!!
That was the subject of discussion a while back. This was one theory:
http://www.urbandictionary.com/define.php?term=******
And for proof please look at the following output from netstat when I have two open connections to MySQL on my localhost system
Proto Local Address Foreign AddressState
TCPCHEF2:3306 CHEF2:4705 ESTABLISHED
TCPCHEF2:3306 CHEF2:4706 ESTABLISHED
TCPCHEF2:4705 CHEF2:3306 ESTABLISHED
TCPCHEF2:4706 CHEF2:3306 ESTABLISHED
Do you see how both connections are represented by two sockets? Do you see which piece of information is different?
> > By ****** I was attempting to refer to the
> civillian
> > version of the military HumVee. What's wrong with
> the
> > word ******?!?! Shees!!!
>
>
> That was the subject of discussion a while back. This
> was one theory:
>
> http://www.urbandictionary.com/define.php?term=******
ROFL!
****!
I blame Torgil.
> > > By ****** I was attempting to refer to the
> > civillian
> > > version of the military HumVee. What's wrong
> with
> > the
> > > word ******?!?! Shees!!!
> >
> >
> > That was the subject of discussion a while back.
> This
> > was one theory:
> >
> >
> http://www.urbandictionary.com/define.php?term=******
>
> ROFL!
>
> ****!
>
> I blame Torgil.
That's not very nice.
> > > > I blame Torgil.> > That's not very nice.Torgil! Wow. What are the chances? How have you been man? I am in the mood for a river dwelling African mammal myself.
I meant from the point of view of a port scan or a netstat. I tend not to refer to localPort() at all, because the name seems misleading to me.
I don't know from your MYSQL port numbers. I know that when I put a server socket up on a port 1234, 1234 [generally] stays in the LISTENING mode, which the actual communication is switch over to another port.
> I meant from the point of view of a port scan or a> netstat. I tend not to refer to localPort() at all,> because the name seems misleading to me.My natural instincts tell me that you should look at reply 13.
> > >
> > > I blame Torgil.
> >
> > That's not very nice.
>
> Torgil! Wow. What are the chances?
You tell me! Here I log on for the first time in ages, and see my name in the first thread on the first page. That's pretty amazing, if you ask me.
> I don't know from your MYSQL port numbers. I know
> that when I put a server socket up on a port 1234,
> 1234 [generally] stays in the LISTENING mode, which
> the actual communication is switch over to another
> port.
*sigh*
Please save compile and run the following. When it says run netstat-a and see what it has to say.
import java.net.*;
import java.util.*;
public class PortTesting implements Runnable{
public static void main(String args[])throws Exception{
Thread t = new Thread(new PortTesting());
t.start();
Thread.currentThread().sleep(4000);
Socket[] sockets = new Socket[10];
for(int i=0;i<sockets.length;i++){
sockets[i] = new Socket("localhost",9000);
Thread.currentThread().sleep(2000);
}
System.out.println("All sockets connected... now sleeping so you can netstat the results");
Thread.currentThread().sleep(60000);
}
public void run(){
try{
List clients = new LinkedList();
ServerSocket ss = new ServerSocket(9000);
while(true){
Socket s = ss.accept();
System.out.println("Server got new client!");
clients.add(s);
}
}catch(Exception e){
System.out.println("Server blew up!");
e.printStackTrace();
}
}
}
>
> > > >
> > > > I blame Torgil.
> > >
> > > That's not very nice.
> >
> > Torgil! Wow. What are the chances?
>
> You tell me! Here I log on for the first time in
> ages, and see my name in the first thread on the
> first page. That's pretty amazing, if you ask me.
After 3 months you show up for 5 minutes and I miss it? :(
PS I'm not sure what I was thinking with the thread sleep at the end... I guess I though the client sockets would get disconnected if gc was run when the main finishes... anyway it's unneccssary.
Well it still does say listening...too. So there! Nyeah! heh
> Well it still does say listening...too. So there!> Nyeah! hehYes I know the listening one is mentioned as well.. but you do see that there are 10 sockets with the port 9000 as remote, 10 as the local the listening local with 0 remote? Right?
Yes, I see that. I'm wrong. Kudos already.What it really comes down to is the original post makes even LESS sense.
> What it really comes down to is the original post> makes even LESS sense.That's what reply 3 is about. This is seems to be a common mispercepion and leads to people trying do strange things ala the OP.
Well, I'll be buggered by yawmark's goat while goldie's GF videotapes it.
I knew, with absolute certainty--and I would have sworn that I observed--that the ServerSocket, after accepting, handed the connection off to a different port.
I even modified your code a bit, and ran the server on one box and the client on another, just in case there was some sort of "short-circuiting" going on when both had the same IP address (not that I thought that was the case, just being thorough).
****** all.
import java.net.*;
import java.util.*;
public class PortTestingServer {
public static void main(String args[])throws Exception{
ServerSocket ss = new ServerSocket(9000);
while(true){
Socket s = ss.accept();
System.out.println("Server got new client! local: " + s + ", remote: " + s.getRemoteSocketAddress());
}
}
}
import java.net.*;
import java.util.*;
public class PortTestingClient {
public static void main(String args[])throws Exception{
Socket[] sockets = new Socket[10];
for(int i=0;i<sockets.length;i++){
sockets[i] = new Socket("shinchan",9000);
System.out.println("Client connected on local: " + sockets[i] + ", remote: " + sockets[i].getRemoteSocketAddress());
Thread.currentThread().sleep(2000);
}
System.out.println("All sockets connected... now sleeping so you can netstat the results");
Thread.currentThread().sleep(60000);
}
}
Server:
:; java -cp . PortTestingServer
Server got new client! local: Socket[addr=/192.168.0.101,port=2874,localport=9000], remote: /192.168.0.101:2874
Server got new client! local: Socket[addr=/192.168.0.101,port=2875,localport=9000], remote: /192.168.0.101:2875
Server got new client! local: Socket[addr=/192.168.0.101,port=2876,localport=9000], remote: /192.168.0.101:2876
etc.
Client:
:; java -cp . PortTestingClient
Client connected on local: Socket[addr=shinchan/192.168.0.103,port=9000,localport=2874], remote: shinchan/192.168.0.103:9000
Client connected on local: Socket[addr=shinchan/192.168.0.103,port=9000,localport=2875], remote: shinchan/192.168.0.103:9000
Client connected on local: Socket[addr=shinchan/192.168.0.103,port=9000,localport=2876], remote: shinchan/192.168.0.103:9000
etc.
>
jverda at 2007-7-20 20:58:11 >

> Well, I'll be buggered by yawmark's goat while
> goldie's GF videotapes it.
>
Can I get some money for my therapy please?
> I knew, with absolute certainty--and I would
> have sworn that I observed--that the
> ServerSocket, after accepting, handed the connection
> off to a different port.
>
To be honest I once thought there was something like happening as well... until I looked at a netstat on a server one time and I realized that is not the case... But when I saw that each socket as a whole was unique a little lightbulb went off.
Anyway I am glad someone else can bang on this drum now because it really is a popular misconception and I have seen people puzzling over it like the OP time and again.
:D
Thank you for trying it though. I do appreciate that and the feedback.
jverda at 2007-7-20 20:58:11 >

> Thank you for trying it though. I do appreciate that> and the feedback.Well it's not like I was just gonna let you shred my beliefs without a challenge. :-)
jverda at 2007-7-20 20:58:15 >

I think you haven't to define a method Connecting() and call it every time you want to establish a new conection: you should define a class in which the code you wrote in method Connecting() is placed in the main() method of this class. Otherwise you shuold eliminated instruction
-break- in your while infinite cicle.
Then you should define a Client class in which there is a main() method: this method simly performs the connection to the ServerSocket (creating a socket and passing ServerSocket port number... and localhost ip_address if you are working on your local machine)
For every client you want to create, call a -new- of the client class described above.... and then call ther main() method
I hope these informations will help you!!
Bye!!
jverd, same here. I VIVIDLY remember that behavior of handing it off to another port.
OK, ok, so, ok, so...at the something-or-other level, the incoming IP packet is examined for the target port number, and ALSO for the source port number, and only then routed up the chain, ultimately either the ServerSocket or the Socket, depending on whether a connection already exists...?
Are we sure it's always worked this way? Is this a java specific thing? Do other environment handling it differently? I can't kick this belief that I've seen the port handed off and I want to understand why my brain's farting.
Can I allowed to say farting here?
> jverd, same here. I VIVIDLY remember that behavior of
> handing it off to another port.
Honestly I don't think so.
There are applications (FTP I think being one) where multiple sockets are opened.. one for control, one for transmission etc.
The reason I think this is... think about the ease of implementing a TCP network with this model vs doing it with your secret port switching. Because if you did switch ports on one side the client would have to know about it. Along with any firewalls... routers... other network components along the way.
Firewalls alone would be insanely complicated to implement.
>
> OK, ok, so, ok, so...at the something-or-other level,
> the incoming IP packet is examined for the target
> port number, and ALSO for the source port number, and
> only then routed up the chain, ultimately either the
> ServerSocket or the Socket, depending on whether a
> connection already exists...?
Remember a ServerSocket binds to the port and returns Sockets. From the Java point of view A Socket is a Socket. I think if you want more on this you will have to get into the TCP guts at a more close and personal level.
I think part of the confusion arises from thinking that a port is a physical idea rather than a virtual one. I mean all those ports are on the same physical NIC and it sorts that out okay.
>
> Are we sure it's always worked this way? Is this a
> java specific thing? Do other environment handling it
> differently? I can't kick this belief that I've seen
> the port handed off and I want to understand why my
> brain's farting.
>
See my previous comments but yes it has always worked this way and no it's not Java specific. That's why I showed you the MySQL example first.
> Can I allowed to say farting here?
Yes but I think it would be better if you didn't.
> OK, ok, so, ok, so...at the something-or-other level,
> the incoming IP packet is examined for the target
> port number, and ALSO for the source port number, and
> only then routed up the chain, ultimately either the
> ServerSocket or the Socket, depending on whether a
> connection already exists...?
Um, not exactly. AFAIK, the ServerSocket is there only to establish the connection, and any IP packets would only be sent after that has already happened.
> Are we sure it's always worked this way? Is this a
> java specific thing? Do other environment handling it
> differently? I can't kick this belief that I've seen
> the port handed off and I want to understand why my
> brain's farting.
I'm pretty sure Java uses the native network libraries the same way you or I would in a C program, and I doubt there's been some major shift in that across multiple platforms recently. And the only socket programming I've done in the last 5 years or more has been Java, so when I thought I saw it, it was almost certainly with Java.
> Can I allowed to say farting here?
Sure, as long as you don't talk about **** farting, or farting while eating a *******.
jverda at 2007-7-20 20:58:15 >

> > Well, I'll be buggered by yawmark's goat while> > goldie's GF videotapes it.> Can I get some money for my therapy please?Why you can get the vid on BT now?
mlka at 2007-7-20 20:58:15 >

Hi all,
Thanks a lot for your help. I understand the concept of socket. I know I shouldn't write a program in this way.
However the problem of my program exists because I create the ServerSocket in a Thread. And the thread is defined within a method.
The first time I called the method, the thread started and a ServerSocket was setup at, for example, port 1234. Then the thread continued to run, everything's fine and then went back to the main program when the thread was finished. However the second time I called the same method, it didn't work because the command within the thread:
ServerSocket ss = new ServerSocket(1234);
returns an exception: Address already in used, JVM_bind
So this is the problem. So as what I read from the replies, this happened because the ServerSocket that I created during the thread was running at the first time was still there even the thread was finished. So I assume there must be a way to shut down the ServerSocket before the end of the first thread.
Would you please advise if it is possible to do that?
Thank you so much for all your help.
Best regards,
Jackie
> Hi all,
>
> Thanks a lot for your help. I understand the concept
> of socket. I know I shouldn't write a program in this
> way.
Yes. That's an important point to remember.
>
> However the problem of my program exists because I
> create the ServerSocket in a Thread. And the thread
> is defined within a method.
>
Okay. But you really should reconsider this choice because this is a baaaad idea.
> The first time I called the method, the thread
> started and a ServerSocket was setup at, for example,
> port 1234. Then the thread continued to run,
> everything's fine and then went back to the main
> program when the thread was finished. However the
> second time I called the same method, it didn't work
> because the command within the thread:
>
> ServerSocket ss = new ServerSocket(1234);
>
> returns an exception: Address already in used,
> JVM_bind
>
> So this is the problem. So as what I read from the
> replies, this happened because the ServerSocket that
> I created during the thread was running at the first
> time was still there even the thread was finished. So
> I assume there must be a way to shut down the
> ServerSocket before the end of the first thread.
>
Yes.
> Would you please advise if it is possible to do
> that?
>
I am unsure if I should give you advice so that you can blow your proverbial legs off.
But call close on the ServerSocket. That would be key.
Thanks mate. I just figured it out. I was too stupid that I didn't put serverSocket.close( ) at the end.
I have spent two whole days on solving it ...........
Thanks again for all your help :)
On the other hand, as I said before, I should have designed my program in this way, but it's just too hard for me to re write everything as this program is part of my final year project and will due in two weeks.
I guess from now on I will plan seriously before I start programming.
Thanks again :)
Don't forget about the Dukes.
> On the other hand, as I said before, I should have
> designed my program in this way, but it's just too
> hard for me to re write everything as this program is
> part of my final year project and will due in two
> weeks.
Is it really that much work to just move the new ServerSocket out of that method to someplace where it will only be called once, and then put an accept call in its place?
jverda at 2007-7-20 20:58:16 >

Hi all,
I have another question.
I create the serverSocket in a thread. If I exit the thread without closing the serverSocket, the serverSocket will be there forever and as the thread has been done, there is no reference to that serverSocket (that's what I think).
Can you please advise if there is a way to close such a serverSocket ? Please note that I can't close it before end of thread because of some reasons.
Thanks again :)
Cheers,
Jackie
..how do you exit the thread? you mean destory() it? the thread won't quit while it's waiting for a blocking operation to complete (like waiting for connections)....
> Hi all,
>
> I have another question.
>
> I create the serverSocket in a thread. If I exit the
> thread without closing the serverSocket, the
> serverSocket will be there forever and as the thread
> has been done, there is no reference to that
> serverSocket (that's what I think).
>
> Can you please advise if there is a way to close such
> a serverSocket ? Please note that I can't close it
> before end of thread because of some reasons.
>
Please elaborate on your "reasons". Because the answer is there is no such reason.
Why would a thread exit?
a) you get to the end of the run
b) some unhandled exception or error is thrown
And you can deal with both of those cases.
Sorry that my question is a bit confusing. Maybe I should ask in this way.
How can I terminate or kill a thread from outside the thread, eg. the main program?
for example,
class A extends Thread {
........
pubilc void run ( ) {
Q q = new Q( );
q.SetupSocket ( );
}
public class test {
public static void main(String args[ ]) {
A a = new A( );
a.start( );
}
So I would like to ask if it is possible to kill the thread from the main class.
To go one step further, as I mentioned before, a serverSocket will be created with in the thread. So in this case, refering to the code above, a serverSocket will be created by calling the SetupSocket ( ) method of an instance, q , of class Q.
So I would also like to ask if it is possible to close the serverSocket from the main class as well.
Thanks you very much.
Regards,
Jackie
Revisit reply 9 please. See the somebooleansemaphore? That is how. A or Q or whatever alphabet letter you are on should have a way so that the other alphabet letter or whatnot can tell it to stop.
Guest at 2007-7-20 20:58:20 >
