Socket locked when performing data exchange

0

I am trying to execute server and client code in Java for the client to send a String , the server to process and return it and the client to receive.

The customer is always kept listening.

But after receiving String it hangs.

Server class

// porta do servidor
    int serverDoor = 4000;

    // numero maximo de conexões que o servidor aceita
    int maxConnections = 10;

    // servidor socket
    ServerSocket server = null;

    // conexão socket
    Socket connection = null;

    // saida dos dados
    OutputStream output = null;

    // entrada dos dados
    InputStream input = null;

    try {

            server = new ServerSocket(serverDoor, maxConnections);

            while (true) {

            System.out.println("Esperando cliente");

            connection = server.accept();

            // abrindo o stream de saida
            output = connection.getOutputStream();
            output.flush();

            // abrindo o stream de entrada
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            // recebendo
            String teste = bufferedReader.readLine();

            output.write("Teste".getBytes());
            output.flush();

        }

    } catch (IOException e) {

        e.printStackTrace();

    } finally {

        try {

            if (output != null) {
                output.close();
            }

            if (input != null) {
                input.close();
            }

            if (connection != null) {
                connection.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }           
}

Client Class

Socket client;
OutputStream output;
InputStream input;

// Step 1: Create a Socket to make connection
client = new Socket(InetAddress.getByName(url), porta);
//client.setSoTimeout(15000); // 5 segundos

// Step 2: Get the input and output streams
output = client.getOutputStream();
output.flush();
input = client.getInputStream();

// Step 3: Process connection
output.write(msg.getBytes());
output.flush();

// recebendo
System.out.println("Antes de receber cliente");
StringBuilder sb = new StringBuilder();
int temp;
while ((temp = input.read()) > -1)
    sb.append((char) temp);
System.out.println("Depois de receber cliente");

// Step 4: Close connection
if (output != null)
    output.close();
if (input != null)
    input.close();
if (client != null)
    client.close();

return sb.toString();

}

After the method of receiving the String it to, I use Windows 8, I do not know if this might represent something.

    
asked by anonymous 18.03.2014 / 15:36

2 answers

2

You need to close the output on the server so that the client understands that the message is gone:

// recebendo
String teste = bufferedReader.readLine();

output.write("Teste".getBytes());
output.flush();
output.close();

And the server can also hang if the client does not return a \ n at the end of the message according to the BufferedReader # readLine ()

// Step 3: Process connection
output.write(msg.getBytes());
output.write('\n');
output.flush();

One suggestion to improve your code would be to use PrintWriter and BufferedReader on both the client and the server. You are using different forms of reading and writing.

Here's a detailed example .

    
18.03.2014 / 18:35
2

In the server class, the closing of the output stream is in an improper place, the finally. This finally will only execute when the try scope comes to an end, ie when the looping finishes, but it is infinite, and "never" will be closed and therefore the client "hangs".

The client is "locked", or better, waiting for more bytes in this section:

...
// recebendo
System.out.println("Antes de receber cliente");
StringBuilder sb = new StringBuilder();
int temp;
while ((temp = input.read()) > -1)
        sb.append((char) temp);
System.out.println("Depois de receber cliente");
...

The only termination condition of while is read() return -1 (or less), which usually will only occur when there is a stream end of data via close() on the server (and network problems, etc). So, the call of the input.read () method freezes, because the output of the server is still open and as a consequence the input of the client is waiting for more data and if it has the impression that it "crashed";

Finally, the purpose of the looping in this question is to treat a connection for each client, as consequently the input and output are instantiated to each accept () of the instance of ServerSocket and therefore must be closed at each iteration. For this you can close the connection, because it will be in charge of closing everything that is pending.

Following this reasoning the source code for the server would look like this:

// porta do servidor
int serverDoor = 4000;

// numero maximo de conexões que o servidor aceita
int maxConnections = 10;

// servidor socket
ServerSocket server = null;

try {

    server = new ServerSocket(serverDoor, maxConnections);

    while (true) {

        System.out.println("Esperando cliente");

        // conexão socket, dentro do looping
        Socket connection = null;

        // saida dos dados, dentro do looping
        OutputStream output = null;

        // aceitando a conexão
        connection = server.accept();

        // abrindo o stream de saida
        output = connection.getOutputStream();
        output.flush();

        // abrindo o stream de entrada
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        // recebendo
        String teste = bufferedReader.readLine();

        output.write("Teste".getBytes());
        output.flush();

        // fechando tudo!
        connection.close();
    }

} catch (IOException e) {

    e.printStackTrace();

}
    
18.03.2014 / 19:40