import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
import java.net.*;


class ConcorrenciaServidor2 implements Runnable 
{
    private Socket cliente = null;
    private DataInputStream in = null;
    private DataOutputStream out = null;
    private BufferedOutputStream bout = null;
    private JTextArea textArea;
    private int loop;
  
    ConcorrenciaServidor2(Socket scktCliente, JTextArea textArea, int aloop) 
    {
        try
        {
           this.in = in;
           loop = aloop;
           this.cliente = scktCliente;
           in = new DataInputStream(this.cliente.getInputStream());
           bout = new BufferedOutputStream(this.cliente.getOutputStream());
           out = new DataOutputStream(bout);
           out = new DataOutputStream(this.cliente.getOutputStream());
           this.textArea = textArea;   
        }
            catch (IOException e) 
            {
                System.out.println("Erro ao criar Streams");
            }
            catch (Exception e) 
            {
                System.out.println("Erro ao criar Streams 2");
            }
    }

    private synchronized void EnviarArquivo1()
    {
	int tam, i, trc=0;
        byte msgLida[];
        String str;
        DataOutputStream outAux;

         try
         {
           tam = in.readInt();
           msgLida = new byte[tam];
           in.read(msgLida);
           str = new String(msgLida);
           trc = 1;

           out.writeInt(tam);
           out.write(msgLida, 0, tam);
           for (i = 0; i < loop; i++)
           {
              out.writeInt(0);
              out.writeInt(7);
              out.write("pagina ".getBytes(), 0, 7);
              out.writeInt(i);
           }
           out.writeInt(-1);
           trc = 2;

           bout.flush();
           trc = 3;
        }
        catch (IOException e) 
        {
            System.out.println("erro no metodo trace: " + trc);
            e.printStackTrace();
        }
        catch (Exception e) 
        {
            System.out.println("erro no metodo2 trace: " + trc);
        }

        try
        {
            cliente.close();
        }
        catch (IOException e) 
        {
            System.out.println("erro no close");
            e.printStackTrace();
        }
        catch (Exception e) 
        {
            System.out.println("erro no close2");
        }
    }

    public void run()
    {
            try
            {
                int op = in.readInt();

		switch (op)
                {
		   //case 0: CalcularSoma();
                   case 1: EnviarArquivo1();
                }
            } 
            catch (IOException e) 
            {
                System.out.println("Erro no run");
                e.printStackTrace();
            }
            catch (Exception e) 
            {
                System.out.println("Erro no run 2");
            }
    }
}


class Servidor2 extends JFrame implements ActionListener
{
    JLabel label = new JLabel("Chamadas dos clientes:");
    JScrollPane scrollPane;
    JPanel panel;
    JPanel panel2;
    JButton botao;
    JTextField edt;
    JTextArea textArea = new JTextArea(13, 28);
    int loop = 100;

    ServerSocket servidor = null;
    int porta;

    Servidor2(int porta)
    {
        panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.setBackground(Color.white);
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(panel, BorderLayout.CENTER);
        textArea.setEditable(false); 

        panel2 = new JPanel();
        panel2.setLayout(new BorderLayout());
        panel2.setBackground(Color.white);
        getContentPane().add(panel2, BorderLayout.SOUTH);
        botao = new JButton("loop");
        panel2.add(botao, BorderLayout.EAST);
        botao.addActionListener(this);
        edt = new JTextField();
        panel2.add(edt, BorderLayout.CENTER);

        scrollPane = new JScrollPane(textArea);
        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add("North", label);

        this.porta = porta;
	loop = 100;
    }

    public void actionPerformed(ActionEvent event)
    {
	loop = Integer.valueOf(edt.getText()).intValue();
    }

    public void socketServidor()
    {
        Socket cliente = null;

        try
        {
            servidor = new ServerSocket(porta); 
        } 
        catch (IOException e) 
        {
            System.out.println("Erro ao criar servidor");
            System.exit(0);
        }
        catch (Exception e) 
        {
            System.out.println("Ocorreu uma falha na criação do servidor!");
            System.exit(0);
        }

        while(true)
        {
            try
            {
                cliente = servidor.accept();

                ConcorrenciaServidor2 chamada = new ConcorrenciaServidor2(cliente, textArea, loop);  
                Thread t = new Thread(chamada);
                t.start();
                System.out.println("Nova conexão");
            } 
            catch (IOException e) 
            {
                System.out.println("Erro ao aceitar conexão");
		break;
            }
            catch (Exception e) 
            {
                System.out.println("Erro ao aceitar conexão 2");
		break;
            }
        }
    }

    protected void finalize()
    {
        try
        {
            servidor.close();
        } 
        catch (IOException e) 
        {
            System.out.println("Erro de I/O ao fechar o socket");
            System.exit(0);
        }
    }

    public static void main(String[] args)
    {
        Servidor2 servidor = new Servidor2(4447);
        WindowListener l = new WindowAdapter() 
                           {
                               public void windowClosing(WindowEvent e) 
                               {
                                   System.exit(0);
                               }
                           };

        servidor.addWindowListener(l);
        servidor.pack();
        servidor.setVisible(true);
        System.out.println("Iniciou servidor");
        servidor.socketServidor();
    }
}

