java.net.SocketTimeoutException的奇怪情况:连接超时

时间:2011-08-26 09:41:06

标签: java multithreading swing sockets

你好,我无法理解一下。简单应用程序中的以下代码完美实现:

     /**
      *
      * @author AKhusnutdinov
      */
     public class JavaApplication12 {

         /**
          * @param args the command line arguments
          */
         public static void main(String[] args) {
             Date startDate = new Date();
             String hostname = "ihtik.lib.ru";
             int port = 80;

             Socket socket = null;
             BufferedReader reader = null;

             try {
                 socket = new Socket();
                 socket.setSoTimeout(30000);
                 socket.connect(new InetSocketAddress(hostname, port),
 30000);
                 String writer = "GET /2011.06.03_prislan.ihtiku/
 HTTP/1.1\r\n"
                         + "Host: " + hostname + "\r\n"
                         + "Accept: */*\r\n"
                         + "User-Agent: Java\r\n"
                         + "\r\n";

 socket.getOutputStream().write(writer.getBytes("UTF-8"));
                 socket.getOutputStream().flush();

                 reader = new BufferedReader(new
 InputStreamReader(socket.getInputStream()));
                 for (String line; (line = reader.readLine()) != null;)
 {
     //                if (line.isEmpty()) {
     //                    break; // Stop when headers are completed.
 We're not interested in all the HTML.
     //                }
                     System.out.println(line);
                 }
             } catch (Exception ex) {
             } finally {
                 if (reader != null) {
                     try {
                         reader.close();
                     } catch (IOException logOrIgnore) {
                     }
                 }

                 if (socket != null) {
                     try {
                         socket.close();
                     } catch (IOException logOrIgnore) {
                     }
                 }
             }

             Date endDate = new Date();
             System.out.println(endDate.getTime() -
 startDate.getTime());
         }
     }

但是在NetBeans中创建的GUI应用程序(桌面应用程序Java,Swing)不能处理相同的代码,但它会出错:

 run: java.net.SocketTimeoutException: Connect timed out
     at
 java.net.SocksSocketImpl.readSocksReply(SocksSocketImpl.java:125)
     at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:459)
     at java.net.Socket.connect(Socket.java:579)
     at
 desktopapplication1.DesktopApplication1View.<init(DesktopApplication1View.java:46)
     at
 desktopapplication1.DesktopApplication1.startup(DesktopApplication1.java:19)
     at
 org.jdesktop.application.Application$1.run(Application.java:171)
     at
 java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
     at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:705)
     at java.awt.EventQueue.access$000(EventQueue.java:101)
     at java.awt.EventQueue$3.run(EventQueue.java:666)
     at java.awt.EventQueue$3.run(EventQueue.java:664)
     at java.security.AccessController.doPrivileged(Native Method)
     at
 java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
     at java.awt.EventQueue.dispatchEvent(EventQueue.java:675)
     at
 java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
     at
 java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
     at
 java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
     at
 java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
     at
 java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
     at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
 ПОСТРОЕНИЕ УСПЕШНО ЗАВЕРШЕНО (общее время: 39 секунд)

零件代码GUI应用程序:

 DesktopApplication1View extends FrameView {

     public DesktopApplication1View(SingleFrameApplication app) {
         super(app);

         initComponents();

         Date startDate = new Date();
         String hostname = "ihtik.lib.ru";
         int portt = 80;

         Socket socket = null;
         BufferedReader reader = null;
         try {
             socket = new Socket();
             socket.setSoTimeout(30000);
             socket.connect(new InetSocketAddress(hostname, portt),
 30000);
             String writer = "GET /2011.06.03_prislan.ihtiku/
 HTTP/1.1\r\n"
                     + "Host: " + hostname + "\r\n"
                     + "Accept: */*\r\n"
                     + "User-Agent: Java\r\n"
                     + "\r\n";
             socket.getOutputStream().write(writer.getBytes("UTF-8"));
             socket.getOutputStream().flush();

             reader = new BufferedReader(new
 InputStreamReader(socket.getInputStream()));
             for (String line; (line = reader.readLine()) != null;) {
 //                if (line.isEmpty()) { //                    break;
 // Stop when headers are completed. We're not interested in all the
 HTML. //                }
                 System.out.println(line);
             }
             reader.close();
             socket.close();
         } catch (Exception ex) {
             ex.printStackTrace();
         }

         // status bar initialization - message timeout, idle icon and
 busy animation, etc
         ResourceMap resourceMap = getResourceMap();
         int messageTimeout =
 resourceMap.getInteger("StatusBar.messageTimeout");
         messageTimer = new Timer(messageTimeout, new ActionListener()
 {
             public void actionPerformed(ActionEvent e) {
                 statusMessageLabel.setText("");
             }
         });

为什么会出错?

1 个答案:

答案 0 :(得分:1)

您正在EventQueue上运行代码。有关此问题的更多信息,请参阅here

代码需要移动到一个单独的线程,只需执行invokeLater()仍然会在事件线程上运行代码。

相关问题