I want to create server which is able to be connected with multiple clients, but I always get 'Socket Closed' exception or read NULL value from input streams, previously I thought it was caused by closing socket connection in a wrong way, so I post this topic, but now seems it's not the problem.
Server Method
//here I use thread pool to solve concurrency issue
public static void main(String[] args) {
try{
ExecutorService service = Executors.newFixedThreadPool(4);
ServerSocket serverSocket = new ServerSocket();
while (true) {
//keep listening
Socket socket = serverSocket.accept();
service.execute(new HandlerThread(socket));
}
}catch(Exception ex){
ex.printStackTrace();
}
}
HandlerThread Class
public class HandlerThread extends Thread{
private Socket socket;
private BufferedReader in;
public HandlerThread(Socket socket) throws IOException {
this.socket = socket;
this.start();
}
public void run(){
try {
//Caches is a singleton class, which used to store the received data from client
Caches caches = Caches.getInstance();
//32 line
in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
String line = in.readLine();
//caches.list is an ArrayList
synchronized (caches.globalCaches) {
if (null != line) {
caches.globalCaches.add(line);
}
}
System.out.println(line);
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client Simulator
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
for(int i = 0 ; i < 40; i++){
Thread.sleep(2000);
test test1 = new test();
test1.start();
}
}
public static class test extends Thread{
public void run(){
try {
Socket socket = new Socket("localhost", 5050);
PrintStream out = new PrintStream(socket.getOutputStream());
out.println("Hello Server!");
out.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Exception and problems
Start server before client simulator, there isn't any exception from client simulator, however within server side, not all data were received, from the console printing information, I saw 'null', 'Hello Server', 'java.net.SocketException: Socket is closed...', like below
Hello Server
null
null
Hello Server
java.net.SocketException: Socket is closed
Hello Server
at java.net.Socket.getInputStream(Socket.java:876)
at com.icubeidea.core.threads.HandlerThread.run(HandlerThread.java:32)
Hello Server
I researched for a quite long time, still can't find what on earth caused those exceptions and data missing issue, and also is there any potential risks which could cause the memory leaking problem after server running for a while?
service.execute(new HandlerThread(socket).start());instead and remove thethis.start()from theHandlerThreadconstructor.