0

再会,

我在 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;
}
4

1 回答 1

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);
}
于 2013-07-07T14:23:54.170 回答