我正在尝试使分布式系统成为一种概念。 我需要接受来自三个不同发件人的3个UDP答复。
我一次可以处理一个请求。但是我如何一次处理3个请求,这样我才能显示3个请求中最好的2个并显示给客户端。
下面以UDPsend()和UDPReply()的形式给出用于处理1个请求的UPD代码。
//这是在3个不同的客户端中编写的send方法
static String UdpSendData(int serverPort,String sSendOutput)
{
DatagramSocket aSocket = null;
String messageReceived = null;
try {
String keywordSent="";
keywordSent=sSendOutput;
aSocket = new DatagramSocket();
byte[] mes = (keywordSent).getBytes();
InetAddress aHost = InetAddress.getByName("192.168.137.1");
DatagramPacket request = new DatagramPacket(mes, (keywordSent).length(), aHost, serverPort);
aSocket.send(request);
byte[] buffer = new byte[1000];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
aSocket.receive(reply);
messageReceived=new String(reply.getData());
System.out.println(messageReceived);
} catch (SocketException e) {
System.out.println("Socket: " + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO: " + e.getMessage());
} finally {
if (aSocket != null)
aSocket.close();
}
return messageReceived;
}
//This is the receive method in which i wanted to have 3 replies
static void UPDRecieve() {
DatagramSocket aSocket = null;
try {
aSocket = new DatagramSocket(7777);
while (true) {
byte[] buffer = new byte[1000];
DatagramPacket request=null;
request= new DatagramPacket(buffer, buffer.length);
aSocket.receive(request);
String ReplyFromServer=new String(request.getData()); //Request received from server
DatagramPacket reply=null;
String Finalmessage="";
System.out.println(ReplyFromServer);
byte[] finalmessage = Finalmessage.getBytes();
reply= new DatagramPacket(finalmessage,Finalmessage.length(), request.getAddress(),request.getPort());
aSocket.send(reply);
}
}
catch (SocketException e) {
System.out.println("Socket: " + e.getMessage());
} catch (IOException e) {
System.out.println("IO: " + e.getMessage());
} finally {
if (aSocket != null)
aSocket.close();
}
}
我需要得到这3个答复,但是如果其中一个有错误或需要时间来执行,如果一个人不响应任何东西而另外两个给出了不同的执行结果,我将如何处理该报价。在这种情况下,我的系统将停止运行,如果它们也同样延迟或bug也将如何等待所有3个执行。如果我得到两个答复,我需要等待第三个答复,那么我将如何等待第三个答复。