🚀 Nuova versione beta disponibile! Feedback o problemi? Contattaci

Esercizi sul Networking in Java

Codegrind Team•Jul 12 2024

Ecco degli esercizi con soluzione per praticare il networking in Java.

Esercizio 1: Creazione di un Client e Server Semplice

Creare un semplice client e server TCP dove il client invia un messaggio al server e il server risponde.

Server.java:

import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(1234)) {
            System.out.println("Server in attesa di connessione...");
            Socket socket = serverSocket.accept();
            System.out.println("Client connesso.");

            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

            String messaggio = in.readLine();
            System.out.println("Messaggio ricevuto dal client: " + messaggio);
            out.println("Messaggio ricevuto: " + messaggio);

            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Client.java:

import java.io.*;
import java.net.*;

public class Client {
    public static void main(String[] args) {
        try (Socket socket = new Socket("localhost", 1234)) {
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            out.println("Ciao, Server!");
            String risposta = in.readLine();
            System.out.println("Risposta dal server: " + risposta);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Esercizio 2: Trasferimento di File

Creare un client e un server TCP che permettano il trasferimento di un file di testo dal client al server.

Server.java:

import java.io.*;
import java.net.*;

public class FileServer {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(1234)) {
            System.out.println("Server in attesa di connessione...");
            Socket socket = serverSocket.accept();
            System.out.println("Client connesso.");

            InputStream inputStream = socket.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream("ricevuto.txt");

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }

            fileOutputStream.close();
            socket.close();
            System.out.println("File ricevuto con successo.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Client.java:

import java.io.*;
import java.net.*;

public class FileClient {
    public static void main(String[] args) {
        try (Socket socket = new Socket("localhost", 1234)) {
            FileInputStream fileInputStream = new FileInputStream("da_inviare.txt");
            OutputStream outputStream = socket.getOutputStream();

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            fileInputStream.close();
            socket.close();
            System.out.println("File inviato con successo.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Esercizio 3: Server HTTP Semplice

Creare un semplice server HTTP che risponda con un messaggio di benvenuto a ogni richiesta GET.
import java.io.*;
import java.net.*;

public class SimpleHttpServer {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
            System.out.println("Server HTTP in attesa di connessione...");

            while (true) {
                try (Socket socket = serverSocket.accept()) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    PrintWriter out = new PrintWriter(socket.getOutputStream());

                    String line;
                    while ((line = in.readLine()) != null && !line.isEmpty()) {
                        System.out.println(line);
                    }

                    String httpResponse = "HTTP/1.1 200 OK\r\n\r\nBenvenuto sul mio server HTTP!";
                    out.write(httpResponse);
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Esercizio 4: UDP Client e Server

Creare un client e un server UDP dove il client invia un messaggio al server e il server risponde.

Server.java:

import java.net.*;

public class UdpServer {
    public static void main(String[] args) {
        try (DatagramSocket socket = new DatagramSocket(1234)) {
            byte[] buffer = new byte[1024];
            DatagramPacket request = new DatagramPacket(buffer, buffer.length);

            System.out.println("Server UDP in attesa di pacchetti...");
            socket.receive(request);

            String messaggio = new String(request.getData(), 0, request.getLength());
            System.out.println("Messaggio ricevuto dal client: " + messaggio);

            String risposta = "Messaggio ricevuto";
            byte[] bufferRisposta = risposta.getBytes();
            DatagramPacket response = new DatagramPacket(bufferRisposta, bufferRisposta.length, request.getAddress(), request.getPort());
            socket.send(response);

            System.out.println("Risposta inviata al client.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Client.java:

import java.net.*;

public class UdpClient {
    public static void main(String[] args) {
        try (DatagramSocket socket = new DatagramSocket()) {
            String messaggio = "Ciao, Server UDP!";
            byte[] buffer = messaggio.getBytes();
            InetAddress address = InetAddress.getByName("localhost");
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, 1234);
            socket.send(packet);

            byte[] bufferRisposta = new byte[1024];
            DatagramPacket response = new DatagramPacket(bufferRisposta, bufferRisposta.length);
            socket.receive(response);

            String risposta = new String(response.getData(), 0, response.getLength());
            System.out.println("Risposta dal server: " + risposta);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Esercizio 5: Multithreaded Server

Creare un server TCP multithreaded che possa gestire più connessioni client contemporaneamente.

Server.java:

import java.io.*;
import java.net.*;

public class MultithreadedServer {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(1234)) {
            System.out.println("Server in attesa di connessione...");
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("Client connesso.");
                new ClientHandler(socket).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class ClientHandler extends Thread {
    private final Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

            String messaggio;
            while ((messaggio = in.readLine()) != null) {
                System.out.println("Messaggio ricevuto: " + messaggio);
                out.println("Echo: " + messaggio);
            }
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Client.java:

import java.io.*;
import java.net.*;

public class MultithreadedClient {
    public static void main(String[] args) {
        try (Socket socket = new Socket("localhost", 1234)) {
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);


 BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            out.println("Ciao, Server!");
            String risposta = in.readLine();
            System.out.println("Risposta dal server: " + risposta);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Esercizio 6: Chat Room di Base

Creare una semplice chat room usando TCP dove i messaggi inviati da un client sono trasmessi a tutti gli altri client connessi.

Server.java:

import java.io.*;
import java.net.*;
import java.util.*;

public class ChatServer {
    private static Set<ClientHandler> clientHandlers = new HashSet<>();

    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(1234)) {
            System.out.println("Chat server in attesa di connessioni...");
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("Client connesso.");
                ClientHandler clientHandler = new ClientHandler(socket);
                clientHandlers.add(clientHandler);
                clientHandler.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static void broadcast(String message, ClientHandler sender) {
        for (ClientHandler clientHandler : clientHandlers) {
            if (clientHandler != sender) {
                clientHandler.sendMessage(message);
            }
        }
    }

    static void removeClient(ClientHandler clientHandler) {
        clientHandlers.remove(clientHandler);
    }
}

class ClientHandler extends Thread {
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);

            String message;
            while ((message = in.readLine()) != null) {
                System.out.println("Messaggio ricevuto: " + message);
                ChatServer.broadcast(message, this);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            ChatServer.removeClient(this);
        }
    }

    void sendMessage(String message) {
        out.println(message);
    }
}

Client.java:

import java.io.*;
import java.net.*;

public class ChatClient {
    public static void main(String[] args) {
        try (Socket socket = new Socket("localhost", 1234)) {
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

            new Thread(() -> {
                String response;
                try {
                    while ((response = in.readLine()) != null) {
                        System.out.println("Messaggio dal server: " + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();

            String userInput;
            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}