-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathClienteSocket.java
More file actions
156 lines (132 loc) · 5.96 KB
/
ClienteSocket.java
File metadata and controls
156 lines (132 loc) · 5.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
/**
* Cliente Socket TCP simples
* Conecta ao ServidorSocket e permite interação via linha de comando
*
* @author Apresentação Java Web
*/
public class ClienteSocket {
private static final String SERVIDOR_HOST = "localhost";
private static final int SERVIDOR_PORTA = 9999;
public static void main(String[] args) {
System.out.println("=== Cliente Socket TCP ===");
System.out.println("Conectando ao servidor " + SERVIDOR_HOST + ":" + SERVIDOR_PORTA);
System.out.println("Certifique-se de que o ServidorSocket está rodando!");
System.out.println();
try (Socket socket = new Socket(SERVIDOR_HOST, SERVIDOR_PORTA);
PrintWriter saida = new PrintWriter(socket.getOutputStream(), true);
BufferedReader entrada = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Scanner scanner = new Scanner(System.in)) {
System.out.println("Conectado com sucesso!");
System.out.println("===========================");
// Thread para receber mensagens do servidor
Thread receptorMensagens = new Thread(() -> {
try {
String mensagemServidor;
while ((mensagemServidor = entrada.readLine()) != null) {
System.out.println(mensagemServidor);
}
} catch (IOException e) {
System.err.println("Conexão com servidor perdida: " + e.getMessage());
}
});
receptorMensagens.setDaemon(true);
receptorMensagens.start();
// Aguardar mensagens iniciais do servidor
Thread.sleep(1000);
// Loop principal para enviar comandos
System.out.println("\n=== Interface de Comandos ===");
while (true) {
System.out.print("> ");
String comando = scanner.nextLine().trim();
if (comando.isEmpty()) {
continue;
}
// Comandos especiais do cliente
if (comando.equalsIgnoreCase("ajuda")) {
mostrarAjudaCliente();
continue;
}
if (comando.equalsIgnoreCase("testar")) {
executarTestesAutomaticos(saida);
continue;
}
if (comando.equalsIgnoreCase("sair")) {
saida.println("QUIT");
Thread.sleep(500); // Dar tempo para o servidor responder
break;
}
// Enviar comando para o servidor
saida.println(comando);
// Se foi QUIT, sair do loop
if (comando.equalsIgnoreCase("QUIT")) {
Thread.sleep(500); // Dar tempo para o servidor responder
break;
}
// Pausa para permitir que a resposta seja exibida
Thread.sleep(100);
}
} catch (IOException e) {
System.err.println("Erro de conexão: " + e.getMessage());
System.err.println("Verifique se o servidor está rodando na porta " + SERVIDOR_PORTA);
} catch (InterruptedException e) {
System.err.println("Thread interrompida: " + e.getMessage());
}
System.out.println("\nCliente desconectado.");
}
private static void mostrarAjudaCliente() {
System.out.println();
System.out.println("=== Ajuda do Cliente ===");
System.out.println("Comandos especiais do cliente:");
System.out.println(" ajuda - Mostrar esta ajuda");
System.out.println(" testar - Executar testes automáticos");
System.out.println(" sair - Desconectar do servidor");
System.out.println();
System.out.println("Comandos do servidor:");
System.out.println(" HELP - Ajuda do servidor");
System.out.println(" TEMPO - Data/hora atual");
System.out.println(" CALC <num1> <op> <num2> - Calculadora");
System.out.println(" ECHO <mensagem> - Repetir mensagem");
System.out.println(" STATUS - Status do servidor");
System.out.println(" QUIT - Desconectar");
System.out.println();
System.out.println("Exemplos:");
System.out.println(" CALC 15 + 25");
System.out.println(" CALC 100 / 4");
System.out.println(" ECHO Olá servidor!");
System.out.println("========================");
}
private static void executarTestesAutomaticos(PrintWriter saida) {
System.out.println();
System.out.println("=== Executando Testes Automáticos ===");
String[] comandosTeste = {
"HELP",
"TEMPO",
"STATUS",
"ECHO Teste automático do cliente",
"CALC 10 + 5",
"CALC 20 - 8",
"CALC 7 * 6",
"CALC 100 / 4",
"CALC 10 / 0", // Teste de divisão por zero
"CALC abc + 5", // Teste de entrada inválida
"COMANDO_INEXISTENTE"
};
for (String comando : comandosTeste) {
System.out.println("Enviando: " + comando);
saida.println(comando);
try {
Thread.sleep(1000); // Pausa entre comandos para ver as respostas
} catch (InterruptedException e) {
System.err.println("Teste interrompido: " + e.getMessage());
break;
}
}
System.out.println("=== Testes Concluídos ===");
}
}