简体   繁体   English

Java套接字编程中的连接拒绝错误

[英]Connection Refused Error in socket programming in java

the snippet of code i'm trying to execute is choosing one file using jFileChooser and retrieve, write that data to Socket. 我要执行的代码段是使用jFileChooser选择一个文件,然后检索并将该数据写入Socket。

  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        File selectedFile;
        FileReader reader = null;
        BufferedReader in;
        try {
            final JFileChooser fc = new JFileChooser();
            fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
            txtSearch.setText((fc.showOpenDialog(CreateNode.this) == JFileChooser.APPROVE_OPTION) ? fc.getSelectedFile().toString() : txtSearch.getText());            
            if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                //gets file from dialog
                selectedFile = fc.getSelectedFile();
                //makes sure files can be processed before proceeding
                if (selectedFile.canRead() && selectedFile.exists()) {
                    System.out.println("can read:"+selectedFile.canRead()+"exists:"+selectedFile.exists());
                    reader = new FileReader(selectedFile);

                }

            }
            in = new BufferedReader(reader);

            //inputLine recieves file text
            String inputLine = in.readLine();
            int LineNumber = 0;
            while (inputLine != null) {
                //LineNumber isn't needed, but it adds a line count on the left, nice
                LineNumber++;
                StringTokenizer tokenizer = new StringTokenizer(inputLine);
                Socket socket=new Socket("localhost",7788);


                //displays text file
                fileData.append(LineNumber + ": " + inputLine + "\n");
                System.out.println("connected:"+socket.isConnected());

                 // ss.accept();
                DataOutputStream dos4=new DataOutputStream(socket.getOutputStream());
                //next line in File opened
                dos4.writeUTF(LineNumber + ": " + inputLine + "\n");
                dos4.close();
                socket.close();
                ServerSocket ss=new ServerSocket(7788);
                Socket socket1=ss.accept();


               DataInputStream inp=new DataInputStream(socket1.getInputStream());
                //String msg=inp.readUTF();
                //System.out.println("msg:"+msg);

               String input = (String)inp.readUTF();
                System.out.println("inputline: "+input);
                ss.close();

            }
            //close stream, files stops loading
            in.close();

// TODO add your handling code here:
    }                                        
    catch (Exception e) {

        System.out.println("Exception e:"+e);
        e.printStackTrace();
        }

    }

I have tried using disabling the firewall and rebuilding the application in netBeans(IDE i'm using) 我尝试使用禁用防火墙并在netBeans中重建应用程序(我正在使用的IDE)

The Error Message is 错误消息是

 can read:trueexists:true
Exception e:java.net.ConnectException: Connection refused: connect
java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
    at java.net.Socket.connect(Socket.java:579)
    at java.net.Socket.connect(Socket.java:528)
    at java.net.Socket.<init>(Socket.java:425)
    at java.net.Socket.<init>(Socket.java:208)
    at com.design.CreateNode.jButton1ActionPerformed(CreateNode.java:194)
    at com.design.CreateNode.access$000(CreateNode.java:29)
    at com.design.CreateNode$1.actionPerformed(CreateNode.java:95)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6505)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3320)
    at java.awt.Component.processEvent(Component.java:6270)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4861)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.java:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2719)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:723)
    at java.awt.EventQueue.access$200(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:682)
    at java.awt.EventQueue$3.run(EventQueue.java:680)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:696)
    at java.awt.EventQueue$4.run(EventQueue.java:694)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:693)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

I have seen suggestions in the google and stcakoverflow also but none of them find useful 我在google和stcakoverflow中也看到了建议,但没有一个有用

As hinted by E_net4 in the comments, you are creating a client before you open the server. 正如注释中的E_net4所暗示的,您在打开服务器之前先创建一个客户端。

My guess is that you followed this approach because of the blocking functionality of the ServerSocket.accept method. 我的猜测是由于ServerSocket.accept方法的阻止功能而采用了这种方法。 A better approach would be to 更好的方法是

  1. Create a server socket 创建服务器套接字
  2. Listen to connections in a seperate thread, where you can safely block without disrupting the main flow 在单独的线程中侦听连接,在此您可以安全地阻塞而不中断主流程
  3. Open your client socket ( Socket class) after your server started listening for connections 服务器开始侦听连接后,打开客户端套接字( Socket类)

It's all a matter of correct ordering 都是正确订购的问题

The server socket must be listening for connections when you try to connect to it. 当您尝试连接到服务器套接字时,它必须正在监听连接。

Try doing the socket stuff in this order: 尝试按以下顺序执行套接字操作:

            ServerSocket ss=new ServerSocket(7788); // Create listening socket.
            Socket socket=new Socket("localhost",7788);  // Connect to listening socket.
            Socket socket1=ss.accept(); // Accept incoming connection.

First create server socket and then socket which will create instance of client socket and then another socket object for accepting the connection. 首先创建服务器套接字,然后创建套接字,该套接字将创建客户端套接字的实例,然后创建另一个接受连接的套接字对象。

ServerSocket ss=new ServerSocket(7777); 
            Socket socket=new Socket("localhost",7777); 
            Socket socket1=ss.accept();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM