I'm having some trouble having more than 1 thread in the code. I get the error:
java.net.BindException: Address already in use: JVM_Bind
Exception in thread "Thread-0" java.lang.NullPointerException
Here is my code:
public static void main( String args[] )
{
Thread t1 = new Thread(new server(1));
t1.start();
Thread t2 = new Thread(new server(2));
t2.start();
}
When the thread t2 code is commented out then it works fine.
Not too sure why I get that error, it doesn't make sense to me. Any help would be appreciated.
You have to change your port for the second ServerSocket
instance, since only one ServerSocket
can be bound to the same port at the same time.
I suggest to improve your server
class with something like this:
public class server {
private static int port = 5000;
public server(int yourParameter) {
/*...*/
service = new ServerSocket(port++);
/*...*/
}
}
This code will allow your servers to be bound to an always increasing port, starting from 5000.