How to put socket in read mode until you receive other java data

Asked

Viewed 150 times

0

I created the server part and the client part. If the message exchange is just an input and an output works perfectly, the problem is to maintain a communication without closing the socket.

In case I send a message to the server, it responds by confirming receipt. On the customer side I send a confirmation of receipt and the server then sends the result of the operation.

Is there any way to make the server-side reading method wait for a new entry? When I do the reading again the method ends up reading the first entry of the customer, as there has not been made a new entry. Could help me ?

Just follow my code...

Client

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

import javax.xml.rpc.ServiceException;

public class Cliente {

    public static void main(String[] args) throws Exception {

        try {

            Socket socket = new Socket("localhost", 40005);
            String resposta = null;
            String mensagem = "#Jose Alvaro#";
            socket.setSoTimeout(18000);
            socket.setTcpNoDelay(true);
            DataOutputStream saida = new DataOutputStream(socket.getOutputStream());
            BufferedReader entrada = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            resposta = enviarSolicitacaoExecucao(entrada, saida, mensagem);
            System.out.println(resposta);
            enviarConfirmacaoRecebimentoResposta(entrada, saida, mensagem, resposta);
            resposta = lerResposta(entrada, (char) 0);
            System.out.println(resposta);
            socket.close();
            /*
             * if(StringUtil.isNull(resposta)){
             * System.out.println("Resposta é nula"); }
             */
            // resposta = limparBinariosResposta(resposta);

        } catch (IOException e) {
            System.out.println(e);
        }
    }

    private static String lerResposta(BufferedReader entrada, char charactereEsperado) throws IOException {

        StringBuilder respostaBuilder = new StringBuilder();
        String resposta = null;

        char[] charBuffer = new char[8192];
        int bytesLidos = 0;
        do {
            try {
                bytesLidos = entrada.read(charBuffer);

            } catch (Exception e) {
                System.out.println("Erro" + e.getMessage());
            }
            respostaBuilder.append(new String(charBuffer, 0, bytesLidos).trim());
        } while (charactereEsperado != 0 && charBuffer[bytesLidos - 1] != charactereEsperado);

        resposta = respostaBuilder.toString();
        // System.out.println(resposta);

        return resposta;
    }

    private static void enviarConfirmacaoRecebimentoResposta(BufferedReader entrada, DataOutputStream saida,
            String mensagem, String resposta) throws IOException, ServiceException {

        /*
         * if (!validarConfirmacaoRecebimento(mensagem.getId(), resposta)) {
         * System.out.
         * println("Resposta não contem confirmação de recebimento do EOC"); }
         * 
         */ String confirmacao = "2 requisicao" + "\n";// mensagem.montarConfirmacao();

        saida.writeBytes(confirmacao);

    }

    private static String enviarSolicitacaoExecucao(BufferedReader entrada, DataOutputStream saida, String mensagem)
            throws IOException {

        String resposta = null;

        String solicitacao = ",,,..PRATPR";

        saida.writeBytes(solicitacao + "\n");
        resposta = lerResposta(entrada, (char) 0);

        return resposta;
    }

}

Server:

public static void main(String[] args) {

     try {

           // Cria um SocketServer (Socket característico de um servidor)
           ServerSocket socket = new ServerSocket(40005);
           System.out.println("Socket iniciado OK");



           while(true) {

               Socket connectionSocket = socket.accept();
               BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

               // Cria uma stream de sáida para retorno das informações ao cliente
               DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

               (new ServidorSoc(connectionSocket,inFromClient,outToClient )).start();
           }
     }
     catch(Exception e){
         System.out.println(e);
     }
 }

}

public void run() {
        try {
            boolean continuar = true;
            while (continuar) {
                int cont = 1;
                String entrada = lerResposta(inFromClient, (char) 0);
                confirmacaoRec = retornarId(entrada) + confirmacaoRec;
                // System.out.println(entrada);
                // converte a resposta pra byte
                byte[] retorno = confirmacaoRec.getBytes();
                // escreve a mensagem no cliente
                outToClient.write(retorno);
                while (continuar) {
                    try {
                        sleep(10000);
                        // inFromClient.wait();
                        retornoCliente = lerResposta(inFromClient, (char) 0);
                        if (!entrada.equals(retornoCliente)) {
                            retorno = resp.getBytes();
                            outToClient.write(retorno);
                            continuar = false;
                        }
                        // System.out.println("Confirmação de recebimento" +
                        // retornoCliente);
                        // if (retornoCliente != entrada && retornoCliente !=
                        // null) {
                        // System.out.println(retornoCliente);
                        // }
                        // }
                        // sleep(1000);

                    } catch (Exception e) {
                        System.out.println(e);
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

    }

    private String retornarId(String entrada3) {
        String[] s = entrada3.split("#");
        String resul = s[1];
        return resul.substring(0, 5);
    }

    private static String lerResposta(BufferedReader entrada, char charactereEsperado) throws IOException {

        StringBuilder respostaBuilder = new StringBuilder();
        String resposta = null;

        char[] charBuffer = new char[8192];
        int bytesLidos = 0;
        do {
            try {
                bytesLidos = entrada.read(charBuffer);

                // System.out.println(bytesLidos);;
            } catch (Exception e) {
                System.out.println("Erro" + e.getMessage());
            }
            respostaBuilder.append(new String(charBuffer, 0, bytesLidos).trim());
        } while (charactereEsperado != 0 && charBuffer[bytesLidos - 1] != charactereEsperado);

        resposta = respostaBuilder.toString();
        // System.out.println(resposta);

        return resposta;
    }

}

1 answer

-1

I built a file server two years ago in college, it’ll solve your problem. It has 3 server instances, a load balance (very simple) and the client part. You start the servers, then load balance and then the client, the sockets await the messages, receive, treat and return a response to the client.

Controller connects to server:

static Socket controladorConectaServidor() {
        try {
            server_socket_alfa = new Socket("localhost", 9700);
            System.out.println("Conexão com AlfaServer realizada");
            return server_socket_alfa;
        } catch (Exception e) {
            System.err.println("Nao consegui conectar com servidor alfa...");
            return null;
        }
    return null;
}

Server:

public class AlfaServer {

    static String endereco = ".\\src\\servidorAlfa\\";
    static ServerSocket serversocket;
    static Socket client_socket;
    static Conexao c;
    static String msg;

    public static void main(String args[]) throws IOException, InterruptedException {

        new AlfaServer();
        do {
            servidorEscutaControlador();
            if (connect()) {

                "AQUI VEM AS FUNÇÕES QUE VOCE PREISA IMPLEMENTAR"
                }
                fechaConexao();
            }
        } while (true);
    }

    static boolean connect() {
        boolean ret;
        try {
            client_socket = serversocket.accept();
            ret = true;
        } catch (Exception e) {
            System.err.println("Não fez conexão" + e.getMessage());
            ret = false;
        }
        return ret;
    }

    static void servidorEscutaControlador() {
        try {
            serversocket = new ServerSocket(9700);
            System.out.println("AlfaServer Escutando na porta: " + serversocket.getLocalPort());
        } catch (IOException e) {
            System.err.println("Não foi possível criar o controlador");
        }
    }

    static void fechaConexao() {
        try {
            client_socket.close();
            serversocket.close();           // fase de desconexão
        } catch (Exception e) {
            System.err.println("Não encerrou a conexão corretamente" + e.getMessage());
        }
    }

}

Connection class:

public class Conexao {

    public static void send(Socket socket, Object obj) {
        ObjectOutputStream out;
        try {

            out = new ObjectOutputStream(socket.getOutputStream());
            out.writeObject(obj);
        } catch (Exception e) {
            System.err.println("Exceção no OutputStream");
        }
    }

    public static Object receive(Socket socket) {
        ObjectInputStream in;
        Object obj = null;
        try {
            in = new ObjectInputStream(socket.getInputStream());
            obj = in.readObject();
        } catch (Exception e) {
            System.err.println("Exceção no InputStream: " + e);
        }
        return obj;
    }
}

File Server (Github)

If you have any questions, text me and I’ll help you

  • 1

    While this link may answer the question, it is best to include the essential parts of the answer here and provide the link for reference. Replies per link only can be invalidated if the page with the link is changed. - Of Revision

  • Thanks for the feedback @hugocsl , improved the response.

Browser other questions tagged

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