I'm working with sockets in java and I was able to find the following problem, writing the server class I sent a message to the client to read, so far, ok !! But when I try to send a message to the server from the client, I can not get the two messages to be read on 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've tried everything, but I could not 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 order respectively! Everything at once is possible?
The output of the Client 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)