日期:2014-05-20  浏览次数:21090 次

socket发出请求对方无应答如何自动关闭socket或报错???

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;


import javax.swing.JOptionPane;

public class Receive extends Thread
{
String friendip;
String receivepath;
DatagramSocket rds;
DatagramPacket rdp;
String msg;
public Receive(String friendip,String receivepath)

this.friendip=friendip;
this.receivepath=receivepath;
    }
public void run()
{
try
{
try
{rds=new DatagramSocket(8880);}
         catch(SocketException e)
         {
         JOptionPane.showMessageDialog(null, "对方无应答!", null, JOptionPane.OK_OPTION);
         System.out.println("对方无应答!");//这个地方想表示没有收到对方的响应后想报错??怎么办?request部分的代码我就不贴上来了,大致就是向另外一台电脑提出请求,然后我想在他不在线的时候,我的电脑能提示对方无应答.
         }
         try
         {
         byte[] rebuf=new byte[256];
             rdp=new DatagramPacket(rebuf, rebuf.length);
             rds.receive(rdp);        
             msg=new String(rebuf,0,rdp.getLength());         
             rds.close();
         }
         catch(IOException e)
         {
         JOptionPane.showMessageDialog(null, "网络通讯出现错误,问题在"+e.toString(), null, JOptionPane.OK_OPTION);
         }
        
         System.out.println("Receive部分完成11111");
         System.out.println("Receive msg(YES/NO):"+msg);         
         if(msg.equals("YES"))
         {
         /*int option = JOptionPane.showConfirmDialog(null,"点击确认下载或取消","P2P",JOptionPane.YES_NO_OPTION);
             if (option == JOptionPane.YES_OPTION)
     {
             download();
     }*/
         System.out.println("Receive部分完成22222");
         JOptionPane.showMessageDialog(null, "点击确认下载", null, JOptionPane.OK_OPTION);
         download();
        
         }
         if(msg.equals("NO"))
         {
         JOptionPane.showMessageDialog(null, "对方不同意共享此文件!", null, JOptionPane.OK_OPTION);
         }
}
catch (Exception e) 
{
e.printStackTrace();
}
    

}
}

------解决方案--------------------
要设置接收延时,在延时时间内没收到回复就会抛出异常