0

目前我有如下代码:

public class CtrlServer {
    private ServerSocket ss;
    private Map<Integer, Socket> s;
    private Map<Integer, PrintWriter> out;
    private Map<Integer, BufferedReader> in;

    public CtrlServer(){
        ss = null;
        s = new HashMap<Integer, Socket>();
        out = new HashMap<Integer, PrintWriter>();
        in = new HashMap<Integer, BufferedReader>();
    }
    public CtrlServer(int port) throws Exception{
        this();
        if(!initialize(port))
            throw new Exception();
    }
    public synchronized boolean initialize(int port){
        try{close();}catch(Exception e){}
        try{
            ss = new ServerSocket(port);
        } catch(Exception e){
            return false;
        }
        return true;
    }
    public boolean getClient(int id, int timeout){
        close(id);
        try{
            ss.setSoTimeout(timeout);
            Socket socket = ss.accept();
            s.put(id, socket);
            in.put(id, new BufferedReader(new InputStreamReader(socket.getInputStream())));
            out.put(id, new PrintWriter(socket.getOutputStream(), true));
            return true;
        }catch (Exception e){
            return false;
        }finally{
            try{ss.setSoTimeout(0);}catch(SocketException e){}
        }
    }
    public synchronized String getResponse(int id, String command){
        try{
            send(id, command);
            String response =  in.get(id).readLine();
            return response;
        }catch(Exception e){
            close(id);
            return null;
        }
    }
    public synchronized void send(int id, String message){
        try{
            out.get(id).println(message);
        }catch(Exception e){}
    }
    public void broadcast(String message){
        for(Entry<Integer, PrintWriter> writer: out.entrySet())
            send(writer.getKey(), message);
    }
    public synchronized boolean isAlive(int id){
        try{
            if(getResponse(id, "alive").equals("OK"))
                return true;
            else
                return false;
        }catch(Exception e){
            close(id);
            return false;
        }
    }
    public synchronized void close(int id){
        try{in.remove(id);}catch(Exception e){}
        try{out.remove(id);}catch(Exception e){}
        try{s.remove(id).close();}catch(Exception e){}
    }
    public void close(){
        try{ss.close();}catch (Exception e){}
        for(Map.Entry<Integer, Socket> client : s.entrySet()){
            close(client.getKey());
        }
    }
}

当想要调用 close() 方法并且在 ReadLine() 部分的 getResponse() 上已经有另一个线程时,问题就出现了

有什么方法可以强制 getResponse 或 bufferedReader.ReadLine() 抛出异常或以某种方式使其停止、释放资源或其他什么?

4

1 回答 1

1

我将创建一个 Handler 实例,它保存您的套接字、输入、输出并为每个处理程序运行一个读取线程。

这将替换和简化这里的大部分共享代码。

于 2013-05-06T17:31:53.197 回答