我正在尝试实现一些与UDP有点不同的东西。
服务器线程接收数据报包,对其进行解析,然后将其传递给适当的线程。如果收到消息,它将回复确认并将其传递给ReceiveMessage线程,后者在屏幕上打印该消息。
我有一个SendMessage线程和ReceiveMessage线程。
我希望SendMessage线程发送一个数据包,并等待特定超时时间的确认。如果服务器收到确认,我想将notify()发送到SendMessage,如果没有收到确认,我希望SendMessage线程超时并在两种情况下执行不同的代码。我该如何实现?
public class ListenThread extends Thread{
protected DatagramSocket socket = null;
protected Boolean on = true;
protected String id;
protected HashMap <String,Contact> people = null;
protected String user;
public ListenThread(String macadd, String user, HashMap <String, Contact> people) throws SocketException
{
super("ListenThread");
this.socket = new DatagramSocket(3333);
this.id=macadd;
this.people = people;
this.user = user;
}
@Override
public void run()
{
while (on)
{
byte[] buf = new byte[256];
try{
// receive request
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String packdetails[] = new String(packet.getData(), 0, packet.getLength()).split(":");//Important part of receiving request. Tool used to parse the request
InetAddress address = packet.getAddress();
if(packdetails[0].equals("D")) // if it's a Detection Packet
{/* Handle what to do with Detection packets */
}// end of small if
}//end of big if
else if(packdetails[0].equals("M"))// implies, Message type packet
{
Timestamp t =new Timestamp(new Date().getTime());
//Send Acknowledgement
String PString = new String("A:"+id);
buf = PString.getBytes();
packet = new DatagramPacket(buf, buf.length, address, 3333);
new ReceiveMessage(packdetails, address, people, t).start();
}
else// if it's an acknowledgemnt
{
//notify the sendmessage thread
}
}//end of try
catch (UnknownHostException e)
{
System.err.print("Unable to find IP of current machine");
}
catch (IOException except)
{
System.err.print("Network Problem : Unable to send packets!");
}
}//end of while
}//end of run
} //课程结束
public class SendMessage extends Thread{
protected Contact person = null;
protected String Message = null;
public SendMessage(Contact person, String Message)
{
this.person=person;
this.Message= Message;
}
@Override
public void run()
{
System.out.println(person.getusername()+": "+Message);
try
{
person.SendMessage(Message);
Thread.currentThread().wait(500);// If i get notify => received acknowledgement
}
catch(IOException e)
{
System.err.println("Unable to send message!");
}
catch (InterruptedException e)
{
System.err.print("Woken before receiving notify");
}
}
最佳答案
要实现此目标,有很多方法,您可以选择CountDownLatch或CyclicBarrier,在其中发件人线程将等待接收者对屏障进行操作。另一种选择是让接收方线程将ack消息放入blockingQueue中,而发送方可以在等待队列时使用队列中的ack。