TCP/IP communication using Socket

Asked

Viewed 658 times

1

I need to do a college job where it is necessary to do a TCP/IP communication something like a "chat chat" is what I have in mind to do. But some questions arose, I don’t know exactly how to ask them so I made a design 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 can heal with the examples from here. But if you can answer in JavaI thank you so much.

First architecture I doubt

inserir a descrição da imagem aqui If this architecture is correct, then I will need to open a Thread for each Private connection that app1 go do? For example: A app1 communicates with the app2 with the porta 99998 and if you are going to talk to app3 will need to make a Thread and communicate with the app3through the porta 99997?

Second architecture I doubt

inserir a descrição da imagem aqui In this architecture all messages will go through Servidor Central and he will be in charge of sending the message to a particular application. If this is the right architecture, how can I make app1talk to the app2? I know you’re gonna go through Servidor Centralbut how will he know that message from app1goes to the app2and not to another? And how do I send the message that’s already on Servidor Centralto the appchosen by app1?

The doubts are those, I hope they are clear, if they are not please ask me to warn you so that I can correct and make as clear as possible.

Maybe the code I made can help in something, I do not know how but I will publish it, is in a very bad way because I do not know totally the methods and I have not formulated a good way to make a better communication.

Clienteum

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
//import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
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);

            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

He’s being called in the code of ServidorUm because it was already a code I 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();
    }
}

Clientetwo ##

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();
    }
}
  • Edit the question and add what you’ve tried to do.

  • Good Articuno... I can’t start an implementation of something without first knowing how it works... So if my question is about how communication works, how can I have something implemented? I haven’t done anything unfortunately, the only thing I can do is edit the question and withdraw the "I’m doing" to "I wish to start a college job", so it helps you?

  • Your question can be considered too wide and be closed, so I gave the hint to add the code, after all there may be N ways to do this, which makes the doubt no longer be specific and be too broad.

  • That’s why I sent two small images asking if any of the two ways are correct, if they are not correct, then it is simply up to who will answer (if you want) send another solution, I am right or wrong?

  • Okay, I just tried to help warn you about the closing (and you already have 2 votes to close this question as broad). It is your choice to apply my tips or not, but if you do not agree, it is your own right.

  • Okay, but like I said above, how am I going to send something implemented, if I don’t have something implemented by not knowing how to start this implementation, agree?

  • Starting point: https://www.devmedia.com.br/java-sockets-creation-comunicacoes-em-java/9465 Ps.: I don’t think using ports is feasible to identify sender and recipient.

  • Thank you Valdeir Psr

  • I added the code, I hope it’s easier now, sorry for the lack of good practices and the "gambiarras" were the ways I found to get them to communicate having little experience with this type of application.

Show 4 more comments

1 answer

0


Perhaps my doubt was not so clear, but I would just like to know how best to make a communication TCP/IP, something like a (CHAT de BATE-PAPO), there are several ways of making a communication TCP/IP, but between the two of the drawing I sent in the question, the best is a structure that uses a SERVIDOR CENTRALas 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 could find.

CENTRAL SERVER

The Servidor Centralin this type of structure it serves to forward the messages that arrive at it to another user who has been 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();
    }
}

Client One

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

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();
    }
}

Client Two

The same goes for 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 treatments are not being done properly, so to function properly you need to follow the steps below:

  1. Perform the Servidor Central, it needs to be spinning to there is the exchange of messages

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

  3. To send files from one client to another it is necessary before uploading them to the server, change the paths of the files in the methods, lerMensagemServidor andescreverMensagemAoServidor of each of the client classes and use the keyword Enviar to trigger the file sending method.

Browser other questions tagged

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