Socket Error (Socket is closed)

0

I'm doing a program using sockets but a very strange error pops up when I sum two numbers twice. The socket goes down and I do not 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();
    }


}
} 

Customer 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   Client2 $ Client.run (Client2.java:211) at   Client2 $ 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)

    
asked by anonymous 10.02.2018 / 18:35

0 answers