Salve a tutti oggi vi volevo chiedere un paio di cose per indrodurre le Socket nelle mie conoscenze. Dopo aver letto qua e la e visto tantissimi esempi, tutti uguali mi chiedevo come fare a fare un collegamento TCP/IP tra due pc diversi quindi non localhost?. Premetto che di Socket non ci ho mai capito niente.
L'esempio che ho visto è questo:
Server.java:
Client.javacodice:import java.io.*; import java.net.*; import java.util.*; public class Server extends Thread { private ServerSocket Server; public static void main(String argv[]) throws Exception { new Server(); } public Server() throws Exception { Server = new ServerSocket(20); System.out.println("Il Server è in attesa sulla porta 4000."); this.start(); } public void run() { while(true) { try { System.out.println("In attesa di Connessione."); Socket client = Server.accept(); System.out.println("Connessione accettata da: "+ client.getInetAddress()); Connect c = new Connect(client); } catch(Exception e) {} } } } class Connect extends Thread { private Socket client = null; BufferedReader in = null; PrintStream out = null; public Connect() {} public Connect(Socket clientSocket) { client = clientSocket; try { in = new BufferedReader( new InputStreamReader(client.getInputStream())); out = new PrintStream(client.getOutputStream(), true); } catch(Exception e1) { try { client.close(); } catch(Exception e) { System.out.println(e.getMessage());} return; } this.start(); } public void run() { try { out.println("Generico messaggio per il Client"); out.flush(); // chiude gli stream e le connessioni out.close(); in.close(); client.close(); } catch(Exception e) {} } }
codice:import java.io.*; import java.net.*; import java.util.*; public class Client { public static void main(String argv[]) { BufferedReader in = null; PrintStream out = null; Socket socket = null; String message; try { // open a socket connection socket = new Socket("localhost", 20); // Apre i canali I/O in = new BufferedReader( new InputStreamReader(socket.getInputStream())); out = new PrintStream(socket.getOutputStream(), true); // Legge dal server message = in.readLine(); System.out.print("Messaggio Ricevuto : " + message); out.close(); in.close(); } catch(Exception e) { System.out.println(e.getMessage());} } }
un esempio migliore puo essere questo : link
Grazie mille, oltre a questo sapreste indicarmi delle guide che approfondiscono questo discorso...

Rispondi quotando
