i have wtited a socket server application in java,it works good but after some connecting and disconnecting of client sockets ,the cpu usage of the application goes above the 65%
are there any problem with my code ?
this is my server application :
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
public class Server {
static final int PORT = 2012;
private static HashSet<DataOutputStream> writers = new HashSet<DataOutputStream>();
public static void main(String[] args) throws Exception {
System.out.println("The chat server is running.");
ServerSocket listener = new ServerSocket(PORT);
try {
while (true) {
new Handler(listener.accept()).start();
}
} finally {
listener.close();
}
}
private static class Handler extends Thread {
private Socket socket;
private DataInputStream in ;
private DataOutputStream out;
public Handler(Socket socket) {
this.socket = socket;
}
public void run() {
try {
in = new DataInputStream(socket.getInputStream()) ;
out =new DataOutputStream(socket.getOutputStream() );
writers.add(out);
while (true) {
byte [] input = new byte [1024];
int count = in.read(input);
if (count > 0) {
for (DataOutputStream writer : writers) {
writer.write(input,0,count);
}
}
if ( input.equals("bye.")) {
break ;
}
}
} catch (IOException e) {
System.out.println(e);
} finally {
if (out != null) {
writers.remove(out);
}
try {
socket.close();
} catch (IOException e) {
}
}
}
}
}