I am trying to create a multi-threaded client-server communication program that uses 2 threads to connect to multiple clients (but only 2 at a time). The characteristics of the program are:
The clients can terminate the communication program from their side but the server thread does not exit.
The threads in the server do not close
ServerSocketuntil the exit condition is fulfilled by the server program, i.e. the server keeps running continuously connecting to various clients if requested.Every time a client terminates the program only the communication (related) streams are closed.
Now the problem is the line of code where the Socket object is created. After calling the accept() method of ServerSocket object, a NullPointerException is thrown. Any insight as to where I am going wrong would be very helpful.
My Server side code:
class Clientconnect implements Runnable
{
ServerSocket ss;
Socket s;
String n;
int f;
Clientconnect() throws Exception
{
new ServerSocket(776);
new Socket();
}
public void run()
{
n = Thread.currentThread().getName();
while(true) // thread iteration
{
try
{
System.out.println("Thread "+Thread.currentThread().getName()+" is ready to accept a
connection.....");
s = ss.accept(); // ------**The NullPointerException occurs here**
System.out.println("Thread "+Thread.currentThread().getName()+" has accepted a connection:\n----------");
PrintStream ps = new PrintStream (s.getOutputStream());
BufferedReader cl = new BufferedReader (new InputStreamReader (s.getInputStream()));
BufferedReader kb = new BufferedReader (new InputStreamReader (System.in));
String in, out;
ps.println("you are connected via thread "+n);
ps.println("----------------------");
while (true)
{
in = cl.readLine();
if( in.equalsIgnoreCase("system_exit"))
{
break;
}
System.out.println("Client : "+in);
System.out.print("Server "+n+" :");
out = kb.readLine();
ps.println(out);
}
s.close();
ps.close();
cl.close();
System.out.print("do you want to close the server socket\n1:close\n2:continue\nenter");
f = Integer.parseInt(kb.readLine());
if(f == 1)
{
ss.close();
break;
}
else
{
continue;
}
}
catch (Exception e){e.printStackTrace();}
}
}
}
class test2g
{
public static void main (String args[]) throws Exception
{
Clientconnect cc = new Clientconnect();
Thread t1 = new Thread (cc, "t1");
Thread t2 = new Thread (cc, "t2");
t1.start();
t2.start();
}
}
It is a fairly simple communications program with no complex resource accessing or retrieval. I am running the client end on the same machine so it's "localhost".
My client side code is merely a reciprocation of the try{} block.
P.S. I have tried declaring the ServerSocket & Socket objects as static in the Clientconnect class but it did not help.
ss, so it'snull.