user4571298
user4571298

Reputation:

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.

  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)

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

Upvotes: 1

Views: 1305

Answers (3)

user4617699
user4617699

Reputation:

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();

Upvotes: 1

As hinted by E_net4 in the comments, you are creating a client before you open the server.

My guess is that you followed this approach because of the blocking functionality of the ServerSocket.accept method. 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

It's all a matter of correct ordering

Upvotes: 2

Klas Lindb&#228;ck
Klas Lindb&#228;ck

Reputation: 33283

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.

Upvotes: 1

Related Questions