Java socket issues, how to send and receive messages simultaneously between client and server?

Asked

Viewed 1,283 times

1

I am working with java sockets and I was able to come across the following problem, writing the server class sent a message to the client to read, so far everything, ok!! But when I try to send a message from the client to the server I cannot, having the two messages read from both sides simultaneously!

What is the problem with these classes?

public class Cliente {

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1", 5000);

        try (Scanner scanner = new Scanner(socket.getInputStream())) {
            System.out.println("Cliente : -- Qual a  mensagem?\n" + scanner.nextLine());
        }

        socket.getOutputStream().write("This is ridiculous!!".getBytes());
        socket.getOutputStream().flush();
    }
}

And in the Server class:

public class Servidor {

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

        ServerSocket server = new ServerSocket(5000);

        while (true) {
            Socket socket = server.accept();
            Scanner entrada = new Scanner(socket.getInputStream());

            try (PrintWriter w = new PrintWriter(socket.getOutputStream())) {
                w.println("Servidor: Java é uma boa linguagem!");
            }
            while (entrada.hasNextLine()) {
                System.out.println(entrada.nextLine());
            }

        }
     }
 }

What should I do? I tried everything, but I couldn’t get the server to write and read a message from the client and also the client to read and write a message to the server, in that same order respectively!
Everything at once is possible?

The output of the Customer class is as follows:

Cliente : -- Qual a  mensagem?
Servidor: Java é uma boa linguagem!
Exception in thread "main" java.net.SocketException: Socket is closed
    at java.net.Socket.getOutputStream(Socket.java:943)
    at aula.ari.teste3.Cliente.main(Cliente.java:21)

2 answers

3

My main language is not Java, so I will try to help you

So I was able to interpret your server code kills the connection to the client as soon as the first message is sent ("Server: Java is a good language!") whereas.hasNextLine() input is false at first, so the infinite loop runs again, accepting new connection and killing existing one due to loss of connection scope.

It is necessary to manipulate your connection while it is active and respond as soon as a new message is received, which is not the case for your code.

Already in the client code you apparently tried to send a message before receiving something from the server, so it is necessary to review the order of this implementation to get the desired result. Only after these adjustments can you interpret what was received between the connections and then respond appropriately.

I hope I’ve helped.

  • 2

    With the creation of a socket you are practically implementing your own protocol, so it would be nice if you set a way to close this connection through the client (for example the http default is " n n" at the end of the string, if keep_alive is not active) and detect through it the closure, preventing the connection from being previously closed by the server. In addition there should also be some control in case the connection is closed improperly (for example a connection drop).

1

This is happening because your door is closed the moment the customer tries to perform this procedure.

Has a nice tutorial on Caelum that can help you, he has an example of Chat, which I believe is more or less what you want: link.

On safety in this procedure

Careful with the implementation of this procedure, it gives a certain freedom to malicious people. When it comes to implementing security you may have a certain difficulty. Avoid sending critical data (user and password, for example), do not accept any kind of data and also define who can use this port, setting the clients by finger.

Is a fairly valid knowledge learn about sockets, but should be used with caution, not just copy code from the internet. In addition, you may have difficulty implementing a security layer.

I also recommend that you see a little about Websockets if your application is web and SSL. If you are Desktop, try encrypt with AES both the information that goes to the server and the information that comes back. It is not the simplest way to implement, but it already makes life difficult for the invader since he will need the keys.

Always remembering that java JAR applications are easily decompilable, then the person who has access to the JAR will have access to the key and consequently to the data.

  • @Andersonbmagalhães Thanks friend , your information is of great value , and in the future I want to deepen in the knowledge of all of them, I want to solve this part of application logic and make them run smoothly!!

Browser other questions tagged

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