Socket Error ( Socket is closed )

Asked

Viewed 870 times

0

I am making a program using sockets but a very strange error appears when I juice two numbers for 2 time. The socket goes down and I don’t know why here is the server code

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Servidor2 {

    public static void main(String[] args) throws IOException {

        new Servidor2();
    }


    ServerSocket servidor;
    ObjectOutputStream resultado;
    ObjectInputStream dados;

    double num1, num2, total = 0.0;
    int operacao;
    char opr = '\n';


    public Servidor2() throws IOException
    {

        JFrame f=new JFrame();  

        JTextField texto = new JTextField(5);
        texto.setEditable(false);
        JButton start=new JButton("Ligar Servidor");  
        JButton stop=new JButton("Parar Servidor");  

        f.add(texto);
        f.add(start);
        f.add(stop);
        f.setLayout(new GridLayout(3,3));  






        start.addActionListener(new ActionListener(){  
            public void actionPerformed(ActionEvent e){  
                texto.setText("servidor inciado!!");
                final Multi3 m1=new Multi3();  
                final Thread t1 =new Thread(m1); 

                t1.start();  
            }
           });






        stop.addActionListener(new ActionListener(){  
            public void actionPerformed(ActionEvent e){  

                    try {

                        texto.setText("servidor desligado");  
                        servidor.close();
                        //t1.stop();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
            }  
            });  

        f.setVisible(true);  
        f.pack();

    }




}

class Multi3 implements Runnable{  
public void run(){  
System.out.println("thread is running...");  
double num1, num2, total = 0.0;
int operacao;
char opr = '\n';

//Cria um socket na porta 12342
ServerSocket servidor;

    try {
        servidor = new ServerSocket(22);
        System.out.println("Porta " + servidor.getLocalPort() + " aberta!");

        // Aguarda alguém se conectar. A execução do servidor
        // fica bloqueada na chamada do método accept da classe
        // ServerSocket. Quando alguém se conectar ao servidor, o
        // método desbloqueia e retorna com um objeto da classe
        // Socket, que é uma porta da comunicação.

        System.out.print("Aguardando conexão do cliente...");
        Socket cliente = servidor.accept();


        System.out.println("\nNova conexao com o cliente " + cliente.getInetAddress().getHostAddress() + cliente.toString());


        ObjectOutputStream resultado = new ObjectOutputStream(cliente.getOutputStream());
        ObjectInputStream dados = new ObjectInputStream(cliente.getInputStream());

        operacao = dados.readInt();
        num1 = dados.readDouble();
        num2 = dados.readDouble();


        switch(operacao)
        {
        case 1:
            opr = '+';
            total = (num1 + num2);

            resultado.writeDouble(total);
            resultado.writeChar(opr);
            resultado.flush();
            break;

        case 2:
            opr = '-';
            total = (num1 - num2);

            resultado.writeDouble(total);
            resultado.writeChar(opr);
            resultado.flush();
            break;
        }


        /*
        if (operacao == 1) {

            opr = '+';
            total = (num1 + num2);

        } else if (operacao == 2) {

            opr = '-';
            total = (num1 - num2);

        } else if (operacao == 3) {

            opr = 'x';
            total = (num1 * num2);

        } else {

            opr = '/';
            total = (num1 / num2);

        }*/


       //resultado.close();
       //dados.close();


        //servidor.close();



    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}
} 

client code

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.EOFException;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class Cliente2{
    public Socket cliente;
    double num1;
    double num2;
    int operacao = 0;
    char opr;

    JTextField texto1 = new JTextField(5);
    JTextField texto2 = new JTextField(5);

    public static void main(String[] args) {

        new Cliente2();

    }

    public Cliente2()
    {

        JFrame f=new JFrame();  

        JButton connect = new JButton("Conectar");
        JButton stop = new JButton("sair");



        JButton sum=new JButton("+");  
        JButton minus=new JButton("-");  
        JButton multiply=new JButton("*");  
        JButton divide=new JButton("/");  

        f.add(connect);
        f.add(stop);
        f.add(texto1);
        f.add(texto2);
        f.add(sum);
        f.add(minus);
        f.add(multiply);
        f.add(divide);

        connect.addActionListener(new ActionListener(){  
            public void actionPerformed(ActionEvent e){  


                 try {
                    cliente = new Socket("127.0.0.1", 22);
                    System.out.println("O cliente conectou ao servidor");
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }


            }
           });

        sum.addActionListener(new ActionListener(){  
            public void actionPerformed(ActionEvent e){  

/*
                try {

                    System.out.println(cliente.isConnected());

                    ObjectInputStream resultado = new ObjectInputStream(cliente.getInputStream());

                   ObjectOutputStream dados = new ObjectOutputStream(cliente.getOutputStream());


                        num1 =  Double.parseDouble(texto1.getText());
                        num2 = Double.parseDouble(texto2.getText());



                        dados.writeInt(1);
                        dados.writeDouble(num1);
                        dados.writeDouble(num2);
                        dados.flush();

                        double total = resultado.readDouble();
                        opr = resultado.readChar();
                        boolean check = true;



                                System.out.println("Total de " + num1 + opr + num2 + " = " + total + " is closed:::: " + cliente.isClosed() + " ?? Is Connected " + cliente.isConnected());






                        resultado.close();
                        dados.close();




                } catch (Exception e1) {
                    e1.printStackTrace();
                }*/

                Client result = new Client();
                result.run();

            }


           });


        minus.addActionListener(new ActionListener(){  
            public void actionPerformed(ActionEvent e){  


                try {

                    System.out.println(cliente.isConnected());

                    ObjectInputStream resultado = new ObjectInputStream(cliente.getInputStream());

                   ObjectOutputStream dados = new ObjectOutputStream(cliente.getOutputStream());


                        num1 =  Double.parseDouble(texto1.getText());
                        num2 = Double.parseDouble(texto2.getText());
                       /* while (!((operacao >= 1) && (operacao <= 4))) {
                            operacao = Integer.parseInt(JOptionPane.showInputDialog("Qual operação desejada? 1= +, 2= -,3= X,4= / "));
                            if (!((operacao >= 1) && (operacao <= 4))) {
                                System.out.println("Você digitou uma operação inválida.");
                            }
                        }*/


                        dados.writeInt(1);
                        dados.writeDouble(num1);
                        dados.writeDouble(num2);
                        dados.flush();

                        double total = resultado.readDouble();
                        opr = resultado.readChar();
                        boolean check = true;



                                System.out.println("Total de " + num1 + opr + num2 + " = " + total + " is closed:::: " + cliente.isClosed() + " ?? Is Connected " + cliente.isConnected());






                        resultado.close();
                        dados.close();

                        //cliente.close();


                        //cliente.close();



                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }



            }


           });


        f.setLayout(new GridLayout(3,3));  

        f.setVisible(true);  
        f.pack();

    }

    /*************************************************/
    class Client extends Thread {
        public void run(){



                System.out.println(cliente.isConnected());

                ObjectInputStream resultado;
                ObjectOutputStream dados;
                try {
                    resultado = new ObjectInputStream(cliente.getInputStream());
                      dados = new ObjectOutputStream(cliente.getOutputStream());




                        num1 =  Double.parseDouble(texto1.getText());
                        num2 = Double.parseDouble(texto2.getText());
                       /* while (!((operacao >= 1) && (operacao <= 4))) {
                            operacao = Integer.parseInt(JOptionPane.showInputDialog("Qual operação desejada? 1= +, 2= -,3= X,4= / "));
                            if (!((operacao >= 1) && (operacao <= 4))) {
                                System.out.println("Você digitou uma operação inválida.");
                            }
                        }*/


                        dados.writeInt(1);
                        dados.writeDouble(num1);
                        dados.writeDouble(num2);
                        dados.flush();

                        double total = resultado.readDouble();
                        opr = resultado.readChar();
                        boolean check = true;



                        System.out.println("Total de " + num1 + opr + num2 + " = " + total + " is closed:::: " + cliente.isClosed() + " ?? Is Connected " + cliente.isConnected());


                           resultado.close();
                           dados.close();

                      // resultado.close();
                       //dados.close();

                        //cliente.close();

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

          }
        }

    /*********************************************/

}

The error that appears in the system is

java.net.Socketexception: Socket is closed
at java.net.Socket.getInputStream(Unknown Source) at Customer2$Client.run(Customer2.java:211) at Cliente2$2.actionPerformed(Customer2.java:121) at javax.swing.Abstractbutton.fireActionPerformed(Unknown Source) at javax.swing.Abstractbutton$Handler.actionPerformed(Unknown Source) at javax.swing.Defaultbuttonmodel.fireActionPerformed(Unknown Source) at javax.swing.Defaultbuttonmodel.setPressed(Unknown Source) at javax.swing.plaf.basic.Basicbuttonlistener.mouseReleased(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.Jcomponent.processMouseEvent(Unknown Source) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.Lightweightdispatcher.retargetMouseEvent(Unknown Source) at java.awt.Lightweightdispatcher.processMouseEvent(Unknown Source) at java.awt.Lightweightdispatcher.dispatchEvent(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.Eventqueue.dispatchEventImpl(Unknown Source) at java.awt.Eventqueue.access$500(Unknown Source) at java.awt.Eventqueue$3.run(Unknown Source) at java.awt.Eventqueue$3.run(Unknown Source) at java.security.Accesscontroller.doPrivileged(Native Method) at java.security.Protectiondomain$Javasecurityaccessimpl.doIntersectionPrivilege(Unknown Source) at java.security.Protectiondomain$Javasecurityaccessimpl.doIntersectionPrivilege(Unknown Source) at java.awt.Eventqueue$4.run(Unknown Source) at java.awt.Eventqueue$4.run(Unknown Source) at java.security.Accesscontroller.doPrivileged(Native Method) at java.security.Protectiondomain$Javasecurityaccessimpl.doIntersectionPrivilege(Unknown Source) at java.awt.Eventqueue.dispatchEvent(Unknown Source) at java.awt.Eventdispatchthread.pumpOneEventForFilters(Unknown Source) at java.awt.Eventdispatchthread.pumpEventsForFilter(Unknown Source) at java.awt.Eventdispatchthread.pumpEventsForHierarchy(Unknown Source) at java.awt.Eventdispatchthread.pumpEvents(Unknown Source) at java.awt.Eventdispatchthread.pumpEvents(Unknown Source) at java.awt.Eventdispatchthread.run(Unknown Source)

  • Here gave u lot of error, minus that of the question. Explain how to simulate the error.

  • Objectinputstream result = new Objectinputstream(.getInputStream() client); basically the socket closes from somewhere

  • There was no error here. You need to explain what you did that triggered this error. Your code has many problems and ta firing a lot of exception, minus the question

  • ok first start the server, then make an account of Umar because I haven’t done the other accounts

  • When you close any of the streams connected to the socket, it also closes. You need to check that it is closed with the method isClosed before invoking a new operation.

  • on the server or client?

  • Where the exception burst.

  • so I basically shut down input and output streams? but I have already close the 2 and continue to close the socket, which continues the error when it receives from the Input object;

  • You don’t understand my comment. That’s why the socket closes. When closing a stream connected to the socket, all streams and the socket itself are closed. You will probably need to reopen each operation.

  • OK with what method then

  • Read my last 3 comments carefully.

  • reopen what in this case?? the socket or the streams

  • All, because when one closes, all are closed. But keep closing each of them separately, to facilitate the life of the garbage collector.

  • ok but could indicate ways of it. for to reopen in this case the streams I see reset method?? of the socket I am still looking for

Show 9 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.