TCP / IP communication using Socket

1

I need to do a college job, where it is necessary to do TCP / IP communication something like a "chat chat" is what I have in mind to do. But some questions have arisen, I do not know exactly how to ask them so I made a drawing in two ways that I think should be the architecture of this type of communication. I'm using the language Java for the program, but I decided not to specify the language in the Title so that if someone from another language has the same doubt it can heal with the examples here. But if you can respond in Java I thank you very much.

First architecture that I doubt about

Ifthisarchitectureiscorrect,thenwillIneedtoopenaThreadforeachPrivateconnectionthatapp1willdo?Forexample:app1communicateswithapp2withporta99998andifincaseyoutalktoapp3youneedtomakeaThreadandcommunicatewithapp3throughporta99997?

SecondarchitecturethatIhavedoubt

InthisarchitectureallmessageswillpassServidorCentralanditwillbeinchargeofsendingthemessagetoacertainapplication.Ifthisisthecorrectarchitecture,howcanImakeapp1talktoapp2?IknowitwillgothroughServidorCentralbuthowwillitknowthatthatmessagefromapp1goestoapp2andnottoanother?AndhowdoIsendthemessagethatisalreadyinServidorCentraltoappchosenbyapp1?

Thedoubtsarethese,Ihopetheyareclear,iftheyarenotpleaseaskmetoalertmesothatIcancorrectandleaveasclearaspossible.

MaybethecodethatIdidcanhelpwithsomething,IdonotknowhowbutI'mgoingtopublishit,it'sinaverybadwaybecauseIdonotknowthemethodscompletelyandIhavenotyetformulatedagoodwaytomakeabettercommunication.

ClientUm

importjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjava.io.BufferedReader;importjava.io.DataInputStream;//importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStreamReader;importjava.net.Socket;publicclassClienteUm{privatestaticSocketsocket;publicstaticvoidmain(String[]args){try{socket=newSocket("127.0.0.3", 12345);

            DataOutputStream fluxoSaidaDados = new DataOutputStream(socket.getOutputStream());

            BufferedReader leitorBuffered = new BufferedReader(new InputStreamReader(System.in));

            escreverMensagemAoServidor(fluxoSaidaDados, leitorBuffered);
            lerMensagemServidor();

        } catch (IOException iec) {
            System.out.println(iec.getMessage());
        }
    }

    private static void escreverMensagemAoServidor(final DataOutputStream fluxoSaidaDados, final BufferedReader leitorBuffered)

            throws IOException {

        new Thread() {
            public void run() {
                String mensagemSaida;
                try {
                    while (true) {
                        mensagemSaida = leitorBuffered.readLine();
                        fluxoSaidaDados.writeUTF("Mensagem do Cliente (1): " + mensagemSaida + "=127.0.0.2");
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();
    }
    private static void lerMensagemServidor() {
        new Thread(){
            public void run(){
                try {
                    DataInputStream fluxoEntradaDados = new DataInputStream(socket.getInputStream());
                    while(true){

                        String mensagemOutroClienteQueVeioPeloServidor = fluxoEntradaDados.readUTF();
                        System.out.println(mensagemOutroClienteQueVeioPeloServidor);
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();
    }
}

Central Server

It is being called in the code of ServidorUm since it was already a code that was testing before.

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.SynchronousQueue;

public class ServidorUm {

    private static ServerSocket servidorSocket;
    private static List<Socket> socketsConectados;

    public static void main(String[] args) {

        try {
            servidorSocket = new ServerSocket(12345);
            socketsConectados = new ArrayList<Socket>();
            do {
                Socket socket = servidorSocket.accept();
                DataInputStream fluxoEntradaDados = new DataInputStream(socket.getInputStream());
                System.out.println("Cliente "+ socket.getLocalAddress().getHostAddress() +" se conectou! ");
                socketsConectados.add(socket);
                lerMensagemDoCliente(fluxoEntradaDados);

            } while (true);

        } catch (Exception e) {
            System.err.println("Ops! " + e.getMessage());
        }
    }

    private static void lerMensagemDoCliente(final DataInputStream fluxoEntradaDados) {
        new Thread() {
            public void run() {
                String mensagemEntrada = "";

                try {
                    while (true) {
                        mensagemEntrada = fluxoEntradaDados.readUTF();
                        String[] teste = mensagemEntrada.split("=");
                        String mensagem = teste[0];
                        String paraQuemEnviar = teste[1];
                        System.out.println("\n" + mensagem);

                        Socket socketQueReceberaMensagem = socketsConectados.stream()
                        .filter(x -> x.getLocalAddress().getHostAddress().equals(paraQuemEnviar))
                        .findFirst().get();

                        DataOutputStream fluxoSaidaDados = new DataOutputStream(socketQueReceberaMensagem.getOutputStream());
                        fluxoSaidaDados.writeUTF(mensagem);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}

ClienteDois ##

import java.io.BufferedReader;
import java.io.DataInputStream;
//import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class ClienteDois {

    private static Socket socket;

    public static void main(String[] args) {

        try {
            socket = new Socket("127.0.0.2", 12345);

            DataOutputStream fluxoSaidaDados = new DataOutputStream(socket.getOutputStream());

            BufferedReader leitorBuffered = new BufferedReader(new InputStreamReader(System.in));

            escreverMensagemAoServidor(fluxoSaidaDados, leitorBuffered);
            lerMensagemServidor();

        } catch (IOException iec) {
            System.out.println(iec.getMessage());
        }
    }

    private static void lerMensagemServidor() {
        new Thread(){
            public void run(){
                try {
                    DataInputStream fluxoEntradaDados = new DataInputStream(socket.getInputStream());
                    while(true){

                        String mensagemOutroClienteQueVeioPeloServidor = fluxoEntradaDados.readUTF();
                        System.out.println(mensagemOutroClienteQueVeioPeloServidor);
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private static void escreverMensagemAoServidor(final DataOutputStream fluxoSaidaDados, final BufferedReader leitorBuffered)
            throws IOException {

        new Thread() {
            public void run() {
                String mensagemSaida;
                try {
                    while (true) {
                        mensagemSaida = leitorBuffered.readLine();
                        fluxoSaidaDados.writeUTF("Mensagem do Cliente (2): " + mensagemSaida + "=127.0.0.3");
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
    
asked by anonymous 06.05.2018 / 18:02

1 answer

0

Maybe my question has not been so clear, but I just want to know how best to make communication TCP/IP , something like (CHAT de BATE-PAPO) , there are several ways to do TCP/IP communication, but between the two of the drawing I sent in the question, the best is a structure that uses SERVIDOR CENTRAL as an intermediary of the information passed by each application connected to it.

So to close the question, I'm going to add my code with this communication made, it was the best way I found it.

CENTRAL SERVER

The Servidor Central in this type of structure it serves to forward messages arriving at it to another user that was requested.

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ServidorCentral {

    private static ServerSocket socketServidorCentral;
    private static List<Socket> socketsConectados;

    public static void main(String[] args) {

        try {
            socketServidorCentral = new ServerSocket(12345);
            socketsConectados = new ArrayList<Socket>();
            do {
                Socket socket = socketServidorCentral.accept();
                ObjectInputStream fluxoEntradaDados = new ObjectInputStream(socket.getInputStream());
                System.out.println("Cliente " + socket.getLocalAddress().getHostAddress() + " se conectou! ");
                socketsConectados.add(socket);
                lerMensagemDoCliente(fluxoEntradaDados);

            } while (true);

        } catch (Exception e) {
            System.err.println("Ops! " + e.getMessage());
        }
    }

    private static void lerMensagemDoCliente(final ObjectInputStream fluxoEntradaDados) {
        new Thread() {
            @SuppressWarnings("unused")
            public void run() {
                String mensagemEntrada = "";

                try {
                    while (true) {

                        Socket socketQueReceberaMensagem = null; // socketsConectados.stream()
                        // .filter(x ->
                        // x.getLocalAddress().getHostAddress().equals(paraQuemEnviar))
                        // .findFirst().get();

                        DadoCompartilhado dadoCompartilhado = (DadoCompartilhado) fluxoEntradaDados.readObject();

                        for (Socket socketConectado : socketsConectados) {
                            if (socketConectado.getLocalAddress().getHostAddress()
                                    .equals(dadoCompartilhado.getEmailEntrega())) {
                                socketQueReceberaMensagem = socketConectado;
                            }
                        }

                        ObjectOutputStream fluxoSaidaDados = new ObjectOutputStream(socketQueReceberaMensagem.getOutputStream());
                        fluxoSaidaDados.writeObject(dadoCompartilhado);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();
    }
}

Customer One

This class will simulate any application that will connect to Servidor Central , it currently only sends messages to another client and if you type Enviar it will send a file, but you must set the path of the file in hand.

/ p>

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

public class ClienteUm {

    private static Socket socket;

    public static void main(String[] args) {

        try {
            socket = new Socket("127.0.0.3", 12345);

            ObjectOutputStream fluxoSaidaDados = new ObjectOutputStream(socket.getOutputStream());

            BufferedReader leitorBuffered = new BufferedReader(new InputStreamReader(System.in));

            escreverMensagemAoServidor(fluxoSaidaDados, leitorBuffered);
            lerMensagemServidor();

        } catch (IOException iec) {
            System.out.println(iec.getMessage());
        }
    }

    private static void escreverMensagemAoServidor(final ObjectOutputStream fluxoSaidaDados,
            final BufferedReader leitorBuffered)

            throws IOException {

        new Thread() {
            public void run() {
                String mensagemSaida;
                try {
                    while (true) {
                        mensagemSaida = leitorBuffered.readLine();
                        DadoCompartilhado dadoCompartilhado = new DadoCompartilhado();
                        dadoCompartilhado.setEmailEntrega("127.0.0.2");
                        dadoCompartilhado.setMensagem("Mensagem do Cliente (1): " + mensagemSaida);

                        if (mensagemSaida.equals("Enviar")){
                            dadoCompartilhado
                                    .setArquivo(new File("C:\Users\Alunos\Desktop\ClienteUm\ImagemQualquer.jpg")); // Caminho de onde será LIDO o arquivo para enviar
                            System.out.println("Arquivo enviado com sucesso!");
                        }

                        fluxoSaidaDados.writeObject(dadoCompartilhado);

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

    private static void lerMensagemServidor() {
        new Thread() {

            public void run() {
                try {
                    while (true) {
                        ObjectInputStream fluxoEntradaDados = new ObjectInputStream(socket.getInputStream());
                        DadoCompartilhado dadoCompatilhado = (DadoCompartilhado) fluxoEntradaDados.readObject();
                        System.out.println(dadoCompatilhado.getMensagem());

                        if (dadoCompatilhado.getArquivo() != null) {
                            InputStream entradaArquivo = null;
                            OutputStream saidaArquivo = null;

                            try {
                                entradaArquivo = new FileInputStream(dadoCompatilhado.getArquivo());
                                saidaArquivo = new FileOutputStream(
                                        new File("C:\Users\Alunos\Desktop\ClienteUm\ImagemClienteUm.jpg")); // Caminho e nome que será gravado o Arquivo

                                byte[] memoriaTemporaria = new byte[1024 * 50];
                                int tamanho;
                                while ((tamanho = entradaArquivo.read(memoriaTemporaria)) > 0) {
                                    saidaArquivo.write(memoriaTemporaria, 0, tamanho);
                                }
                                System.out.println("Recebido com sucesso!");
                            } catch (Exception ex) {
                                System.err.println(ex.getMessage());
                            }
                        }
                    }
                } catch (IOException | ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception ex) {
                    System.out.println("Maior que meus erros");
                }
            }
        }.start();
    }
}

Two Customer

The same applies to this class, which simulates a second application connected to Servidor Central and with the same functions as Cliente Um .

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

public class ClienteDois {

    private static Socket socket;
    private static ObjectOutputStream fluxoSaidaDados;
    private static BufferedReader leitorBuffered;

    public static void main(String[] args) {

        try {
            socket = new Socket("127.0.0.2", 12345);

            fluxoSaidaDados = new ObjectOutputStream(socket.getOutputStream());

            leitorBuffered = new BufferedReader(new InputStreamReader(System.in));

            escreverMensagemAoServidor(fluxoSaidaDados, leitorBuffered);
            lerMensagemServidor();

        } catch (IOException iec) {
            System.out.println(iec.getMessage());
        }
    }

    private static void lerMensagemServidor() {
        new Thread() {

            public void run() {
                try {
                    while (true) {
                        ObjectInputStream fluxoEntradaDados = new ObjectInputStream(socket.getInputStream());
                        DadoCompartilhado dadoCompatilhado = (DadoCompartilhado) fluxoEntradaDados.readObject();
                        System.out.println(dadoCompatilhado.getMensagem());

                        if (dadoCompatilhado.getArquivo() != null) {
                            InputStream entradaArquivo = null;
                            OutputStream saidaArquivo = null;

                            try {
                                entradaArquivo = new FileInputStream(dadoCompatilhado.getArquivo());
                                saidaArquivo = new FileOutputStream(
                                        new File("C:\Users\Alunos\Desktop\ClienteDois\ImagemClienteDois.jpg"));// Caminho e nome que será gravado o Arquivo

                                byte[] memoriaTemporaria = new byte[1024 * 50];
                                int tamanho;
                                while ((tamanho = entradaArquivo.read(memoriaTemporaria)) > 0) {
                                    saidaArquivo.write(memoriaTemporaria, 0, tamanho);
                                }
                                System.out.println("Recebido com sucesso!");
                            } catch (Exception ex) {
                                System.err.println(ex.getMessage());
                            }
                        }
                    }
                } catch (IOException | ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception ex) {
                    System.out.println("Maior que meus erros");
                }
            }
        }.start();
    }

    private static void escreverMensagemAoServidor(final ObjectOutputStream fluxoSaidaDados,
            final BufferedReader leitorBuffered) throws IOException {

        new Thread() {
            public void run() {
                String mensagemSaida;
                try {
                    while (true) {
                        mensagemSaida = leitorBuffered.readLine();
                        DadoCompartilhado dadoCompartilhado = new DadoCompartilhado();
                        dadoCompartilhado.setEmailEntrega("127.0.0.3");
                        dadoCompartilhado.setMensagem("Mensagem do Cliente (2): " + mensagemSaida);
                        if (mensagemSaida.equals("Enviar")){
                            dadoCompartilhado
                                    .setArquivo(new File("C:\Users\Alunos\Desktop\ClienteDois\ImagemQualquer.jpg")); // Caminho de onde será LIDO o arquivo para enviar
                            System.out.println("Arquivo enviado com sucesso!");
                        }

                        fluxoSaidaDados.writeObject(dadoCompartilhado);
                        fluxoSaidaDados.flush();
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();
    }
}

INSTRUCTIONS

Exception handling is not being done correctly, so in order to work properly you need to follow the steps below:

  • Run Servidor Central , it must be running to that there is the exchange of messages

  • Run any of the clients, one or two, but if you start only one and send a message to the other one not started, an error will appear, which will be solved only if the other client is started. li>

  • To send files from one client to another it is necessary before uploading them to the server, changing the file paths in the methods, lerMensagemServidor and escreverMensagemAoServidor of each client class, and use the keyword Enviar to trigger the method of sending files.
  • 10.05.2018 / 23:40