阻止正在打开/正在使用的Java套接字

时间:2013-07-07 13:45:13

标签: java rest tcp connection

美好的一天,

我在java中有一个sendMessage函数,看起来像这样。它目前作为静态方法存在,可以由任何线程操作(例如HTTP请求)调用。但是,如果我要同时发送两个请求。其中一个sendMessage请求将抛出“连接重置”。

我需要知道我当前的端口和IP正在使用中!这样我就不会重置连接,而是等待它再次可用。有办法吗?

private static String sendMessage(int command,String data,int port,String ip){
    try{
        String sendString=Integer.toString(command)+":"+data+'$'+'\n';
        BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
        Socket clientSocket = new Socket();
        InetAddress addr = InetAddress.getByName(ip);
        SocketAddress sockaddr = new InetSocketAddress(addr, port);
        clientSocket.connect(sockaddr, 20000);

        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        outToServer.writeBytes(sendString);
        String rcvString = inFromServer.readLine();
        System.out.println("FROM DEVICE: " + rcvString);
        clientSocket.close();
        return rcvString;
    }catch(Exception e){
        System.err.println(e.getMessage());
    }

    return NULL;
}

1 个答案:

答案 0 :(得分:0)

好吧,我只是想到了一个巧妙的解决方案,但它很难看。

有一个blockChecker类

public class BlockerCheck {

List<String> blockerList;

public BlockerCheck(){
    blockerList=new ArrayList<String>();
}

public synchronized void addBlock(String ip,int port){
    String finalString=ip+":"+Integer.toString(port);
    blockerList.add(finalString);
}

public synchronized void removeBlock(String ip,int port){
    String finalString=ip+":"+Integer.toString(port);
    blockerList.remove(finalString);
}

public synchronized boolean isAvailable(String ip,int port){
    String finalString=ip+":"+Integer.toString(port);
    System.out.println("SIZE:" +blockerList.size());
    return !(blockerList.contains(finalString));
}
}

然后使用它:

private static String sendMessage(int command,String data,int port,String ip){
    if(blockerCheck.isAvailable(ip, port)) blockerCheck.addBlock(ip, port);
    else{
        long startTime=TimeUnit.SECONDS.convert(System.nanoTime(), TimeUnit.NANOSECONDS);
        while(!(blockerCheck.isAvailable(ip, port))){
            long currTime=TimeUnit.SECONDS.convert(System.nanoTime(), TimeUnit.NANOSECONDS);
            if((currTime-startTime)>10) return null; //ensure null handled
        }
    }
      //SENDING CODE HERE
      blockerCheck.removeBlock(ip, port);
}