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)
What is line 21?
– Guilherme Nascimento