
Tag: Programmazione, Internet, Informatica, Java.Visto 945 volte.
Un socket, in generale, è una astrazione fornita dal sistema operativo, che permette l'utilizzo di api standard per la gestione delle comunicazioni su rete.
Nel nostro caso, quello trattato da questa guida, utilizzeremo i socket messi a disposizione dalla Java Virtual Machine per instaurare una comunicazione con un Web Server.
Vediamo quindi ora come si creano e si utilizzano i socket in java per la comunicazione su rete.
Per rendere più facile il testing del nostro programma, abbiamo deciso di testare una connessione ad un Web Server locale, nel nostro caso Apache, che risponderà con la default page:
Vediamo quindi subito nel dettaglio il codice Java che instaura il socket, fa la richiesta HTTP e riceve la risposta dal Web Server.
Code:
import java.net.*;
public class MyFirstSocket {
String host;
Integer port;
Socket sock;
BufferedReader reader;
PrintStream outp;
public MyFirstSocket(String host_,Integer port_)
{
this.host = host_;
this.port = port_;
}
private void creazioneSocket()
{
try
{
this.sock = new Socket(this.host,this.port);
this.reader = new BufferedReader(new InputStreamReader(this.sock.getInputStream()));
this.outp = new PrintStream(this.sock.getOutputStream());
}
catch(Exception e)
{
System.err.println(e.toString());
}
}
private void closeSocket()
{
try
{
this.sock.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
private String scriviSullaSocket(String s)
{
String ret = "";
this.outp.print(s);
this.outp.flush();
try
{
while(!ret.contains("</html>"))
{
ret += this.reader.readLine() + "n";
}
}
catch(Exception e)
{
e.printStackTrace();
}
return ret;
}
public static void main(String[] args)
{
String request = "";
String response = "";
/* INSTANZIO L'OGGETTO MyFirstSocket CON I PARAMETRI HOST=localhost E PORT=80 */
MyFirstSocket s = new MyFirstSocket("localhost",80);
/* UTILIZZO IL METODO creazioneSocket() PER INSTANZIARE LA SOCKET */
s.creazioneSocket();
/* INIZIALIZZO REQUEST OPPORTUNAMENTE PER UNA RICHIESTA HTTP */
request = "GET / HTTP/1.1" + (char)13 + (char)10;
request += "Host: " + s.host + (char)13 + (char)10;
request += "\r\n";
/* UTILIZZO IL METODO scriviSullaSocket() CON PARAMETRO REQUEST=alla mia richiesta http */
response = s.scriviSullaSocket(request);
s.closeSocket();
/* STAMPO L'OUTPUT */
System.out.println("RICHIESTA:");
System.out.print(request);
System.out.println("RISPOSTA:");
System.out.println(response);
}
}
Il file può essere scaricato da qui oppure può essere salvato con copia/incolla da qui sopra salvandolo con il nome MyFirstSocket.java.
Compiliamolo con:
Code:
e mandiamo in esecuzione il file class con
Code:
La risposta che il Web Server dovrebbe darci, che sarà stampata a video, dovrebbe essere una cosa del tipo:
Code:
Date: Tue, 22 Sep 2009 16:00:00 GMT
Server: Apache/2.2.13 (Fedora)
Last-Modified: Wed, 06 May 2009 23:00:40 GMT
ETag: "1847-2d-469465d40d600"
Accept-Ranges: bytes
Content-Length: 45
Content-Type: text/html; charset=UTF-8
<html><body><h1>It works!</h1></body></html>
Potete ora modificare il codice per effettuare comunicazioni di rete differenti, tenendo conto che la base della creazione e utilizzo dei socket rimane identico per qualsiasi protocollo applicativo utilizziate.
Tags
Apache Bash Elastix Firewall Firma digitale Geolocazione Grafica Informatica Internet Java Linux OpenMoko PHP Programmazione Python Reti Ricetta SEO Sicurezza Sistemi Operativi Varie Virtualizzazione VoIPLink ad altri blog:


