How to implement my java program to be Multithread?

Asked

Viewed 201 times

1

My program is not running properly, I can start the server but does nothing else. I want to be able to write a message in the program and have the same message as a response.

This is the client code:

import java.net.Socket;
import java.lang.Thread;

import java.io.*;

public class EchoClient extends Thread {
    Socket connection;

    public EchoClient(Socket socket) 
    {
        this.connection = socket;
    }

    public static void main(String[] args)
    {
        try
        {   
            String host = args[0];
            int port = 4444;

            // conecta ao servidor e abre os streams
            Socket socket = new Socket(host, port);
            System.out.println("\nConectado a " + host + " na porta" + port);

            PrintStream out = new PrintStream(socket.getOutputStream());
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

            Thread thread = new EchoClient(socket);
            thread.start();

            // lê da entrada padrão stdin, envia, escreve resposta
            String s;
            while (true)
            {
                System.out.print("\nEchoServer > ");
                s = in.readLine();
                out.println(s);
            }
        } 
        catch (IOException e)
        {
            System.out.println("Exceção detectada: " + e);
        }
    }

    public void run()
    {
        try
        {
            BufferedReader in = new BufferedReader(new InputStreamReader(this.connection.getInputStream()));

            String s;
            while (true)
            {
                s = in.readLine();
                if (s == null) 
                {
                    System.out.println("Conexão fechada!");
                    System.exit(0);
                }
                System.out.println(s);
                System.out.print("\nMessage > ");
            }
        } 
        catch (IOException e) 
        {
            System.out.println("Exceção detectada: " + e);
        }
    }
}

Server code:

import java.net.Socket;
import java.net.ServerSocket;
import java.lang.Thread;
import java.io.*;

public class EchoServer {
    public static void main(String[] args) throws Exception
    {
        try
        {
            int port = 4444;
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("\nServidor iniciado na porta " + port);

            while(true)
            {
                // espera blocante até alguma requisição de conexão   
                Socket clientSocket = serverSocket.accept();
                System.out.println("\nConexão aceitado do cliente");

                EchoHandler handler = new EchoHandler(clientSocket);
                handler.start();

                System.out.println("Fechando conexão com o cliente"); 
            }
        }
        catch(Exception e)
        {
            System.out.println("Exceção detectada: " + e);
        }
    }
}

class EchoHandler extends Thread
{
    Socket clientSocket;

    EchoHandler (Socket clientSocket) 
    {
        this.clientSocket = clientSocket;
    }

    public void run()
    {
        try
        {
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);                   
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            out.println("Digite 'sair' para desconectar ");

            while (true) 
            {
                String s = in.readLine();
                if (s.trim().equals("quit")) 
                {
                    out.println("Terminado!");
                    out.close();
                    in.close();
                    break;
                }
                out.println(s);
            }
        }
        catch(Exception e)
        {
            System.out.println("Exceção detectada: " + e + "cliente desconectado");
        }
        finally
        {
            try 
            { 
                clientSocket.close(); 
            }
            catch (Exception e ){ ; }
        }
    }
}

What’s wrong with the program?

  • Hello Rodrigo, what exactly would you like to be multi-threaded in this code? Do you want to have different threads handling customer requests? Or just what you wanted was for your program to work (as the answer from saidmrn)

1 answer

1


I tested your code,

  String host = args[0];

To:

        String host ="localhost";

Console:

   Conectado a localhost na porta4444

EchoServer > Digite 'sair' para desconectar 

Message > oi servidor

EchoServer > oi servidor

Message > 

Browser other questions tagged

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