-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCliente.java
More file actions
42 lines (40 loc) · 1.6 KB
/
Cliente.java
File metadata and controls
42 lines (40 loc) · 1.6 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
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Cliente {
public static void main(String[] args) throws IOException {
//cria um socket com o google na porta 80
Socket socket = new Socket("google.com.br", 80);
//verifica se esta conectado
if (socket.isConnected()) {
//imprime o endereço de IP do servidor
System.out.println("Conectado a " + socket.getInetAddress());
}
/* veja que a requisição termina com \r\n que equivale a <CR><LF> para encerar a requisição tem uma linha em branco */
String requisicao = ""
+ "GET / HTTP/1.1\r\n"
+ "Host: www.google.com.br\r\n"
+ "\r\n";
//OutputStream para enviar a requisição
OutputStream envioServ = socket.getOutputStream();
//temos que mandar a requisição no formato de vetor de bytes
byte[] b = requisicao.getBytes();
//escreve o vetor de bytes no "recurso" de envio
envioServ.write(b);
//marca a finalização da escrita
envioServ.flush();
//cria um scanner a partir do InputStream que vem do servidor
Scanner sc = new Scanner(socket.getInputStream());
//enquanto houver algo para ler
while (sc.hasNext()) {
//imprime uma linha da resposta
System.out.println(sc.nextLine());
}
//fechar a conexao
sc.close();
envioServ.close();
socket.close();
System.out.println("Conexao Encerrada!");
}
}