Advertisement
Guest User

Untitled

a guest
Oct 15th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. package pkgSocketTCP;
  2. //Si importano le librerie per effettuare il codice che definisce la connessione
  3. import java.io.IOException;
  4. import java.io.PrintWriter;
  5. import java.net.InetAddress;
  6. import java.net.Socket;
  7. import java.util.Scanner;
  8.  
  9. public class Client {
  10. private Socket socket; //Dichiara la porta(socket) del client
  11. private Scanner scanner;//Lo scanner per avere l'input su console
  12.  
  13. //Costruttore con argomenti l'ip del server a cui connettersi e la sua relativa porta
  14. private Client(InetAddress serverAddress, int serverPort) throws Exception {
  15. //Istanzia il socket e lo scanner per l'input
  16. this.socket = new Socket(serverAddress, serverPort);
  17. this.scanner = new Scanner(System.in);
  18. }
  19.  
  20. //Metodo di lancio/esecuzione del client che rimane in attesa di input dall'utente
  21. private void start() throws IOException {
  22. String input; //dichiara un oggetto input di tipo stringa
  23. //E quando il server sarà attivato
  24. while (true) {
  25. input = scanner.nextLine();
  26. PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true); //Stampa una stringa
  27. out.println(input);
  28. out.flush();
  29. }
  30. }
  31.  
  32. public static void main(String[] args) throws Exception {
  33. //crea un oggetto client
  34. Client client = new Client( InetAddress.getByName(args[0]), Integer.parseInt(args[1])); //Istanzia il client con IP e Porta
  35.  
  36. //Messaggio di servizio per la corretta connessione al server
  37. System.out.println("\r\nConnesso al server: " + client.socket.getInetAddress());
  38.  
  39. //Avvia il client
  40. client.start();
  41. }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement