SocketServer

 avatar
unknown
plain_text
2 years ago
7.2 kB
5
Indexable
public class SocketServer {
    private static final Path JSON_FILE_PATH = Paths.get("C:\\Users\\juhns\\IntelliJ Projects\\Java WebService Task Server\\src\\favorite_music.json");

    public static void main(String[] args) {
        // Define the server port
        int port = 8080;
        // Try with resources block to automatically close the server socket
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            // Print a message indicating the server has started
            System.out.println("Server started on port " + port);
            // Keep accepting client connections indefinitely
            while (true) {
                // Try with resources block to automatically close client sockets and streams
                try (Socket clientSocket = serverSocket.accept();
                     BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                     PrintWriter out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()), true)) {

                    // Variable to store client request
                    String request;
                    // Process client requests until the connection is closed
                    while ((request = in.readLine()) != null) {
                        // Print the received request
                        System.out.println("Received request: " + request);

                        // Process the client request and respond accordingly
                        if ("/GET/ALLSONGS".equalsIgnoreCase(request)) {
                            // Read favorite music from the JSON file
                            JSONArray favoriteMusic = readFavoriteMusicJsonArray();
                            // Send the favorite music data to the client
                            out.println(favoriteMusic.toJSONString());
                        } else if ("GETARTIST".equalsIgnoreCase(request)) {
                            // Prompt the client for the artist name
                            out.println("Enter artist name:");
                            // Read the artist name from the client
                            String artistName = in.readLine();

                            // Read favorite music from the JSON file
                            JSONArray favoriteMusic = readFavoriteMusicJsonArray();
                            // Filter songs by the provided artist name
                            JSONArray artistSongs = new JSONArray();
                            for (Object obj : favoriteMusic) {
                                JSONObject song = (JSONObject) obj;
                                if (artistName.equalsIgnoreCase((String) song.get("artist"))) {
                                    artistSongs.add(song);
                                }
                            }
                            // Send the filtered songs to the client
                            out.println(artistSongs.toJSONString());
                        } else if ("GETSONG".equalsIgnoreCase(request)) {
                            // Prompt the client for the song name
                            out.println("Enter song name:");
                            // Read the song name from the client
                            String songName = in.readLine();

                            // Read favorite music from the JSON file
                            JSONArray favoriteMusic = readFavoriteMusicJsonArray();
                            // Find the requested song
                            JSONObject targetSong = null;
                            for (Object obj : favoriteMusic) {
                                JSONObject song = (JSONObject) obj;
                                if (songName.equalsIgnoreCase((String) song.get("song"))) {
                                    targetSong = song;
                                    break;
                                }
                            }
                            // Send the requested song to the client or a "not found" message
                            if (targetSong != null) {
                                out.println(targetSong.toJSONString());
                            } else {
                                out.println("Song not found");
                            }
                        } else if ("ADDSONG".equalsIgnoreCase(request)) {
                            // Prompt the client for the song name
                            out.println("Enter song name:");
                            // Read the song name from the client
                            String songName = in.readLine();

                            // Prompt the client for the artist name
                            out.println("Enter artist name:");
                            // Read the artist name from the client
                            String artistName = in.readLine();

                            // Create a new JSONObject for the new song
                            JSONObject newMusic = new JSONObject();
                            newMusic.put("song", songName);
                            newMusic.put("artist", artistName);

                            // Read favorite music from the JSON file
                            JSONArray favoriteMusic = readFavoriteMusicJsonArray();
                            // Add the new song to the favorite music array
                            favoriteMusic.add(newMusic);
                            // Write the updated favorite music array back to the JSON file
                            Files.write(JSON_FILE_PATH, favoriteMusic.toJSONString().getBytes(StandardCharsets.UTF_8));

                            // Send a confirmation message to the client
                            out.println("Song added");
                        } else {
                            // Send a generic message to the client if the request is not recognized
                            out.println("Message received!");
                        }
                    }
                    // Catch any IOExceptions that occur while processing client requests
                } catch (IOException e) {
                    // Print an error message with the exception details
                    System.err.println("Error processing request: " + e.getMessage());
                }
            }
            // Catch any IOExceptions that occur while starting the server
        } catch (IOException e) {
            // Print an error message with the exception details
            System.err.println("Error starting server: " + e.getMessage());
        }
    }

    // Define a method to read the favorite music JSON array from the JSON file
    private static JSONArray readFavoriteMusicJsonArray() throws IOException {
        // Read the contents of the JSON file into a string
        String content = new String(Files.readAllBytes(JSON_FILE_PATH), StandardCharsets.UTF_8);
        // Parse the JSON string and return it as a JSONArray
        return (JSONArray) JSONValue.parse(content);
    }
}
Editor is loading...