SocketServer

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.7 kB
1
Indexable
Never
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

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) {
        int port = 8080;
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Server started on port " + port);
            while (true) {
                try (Socket clientSocket = serverSocket.accept();
                     BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                     PrintWriter out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()), true)) {

                    String request;
                    while ((request = in.readLine()) != null) {
                        System.out.println("Received request: " + request);

                        if ("GET".equalsIgnoreCase(request)) {
                            JSONArray favoriteMusic = readFavoriteMusicJsonArray();
                            out.println(favoriteMusic.toJSONString());
                        } else if (request.startsWith("POST ")) {
                            String requestBody = request.substring(5);
                            JSONObject newMusic = (JSONObject) JSONValue.parse(requestBody);

                            JSONArray favoriteMusic = readFavoriteMusicJsonArray();
                            favoriteMusic.add(newMusic);
                            Files.write(JSON_FILE_PATH, favoriteMusic.toJSONString().getBytes(StandardCharsets.UTF_8));

                            out.println("Message received");
                        } else {
                            out.println("Unknown request");
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Error processing request: " + e.getMessage());
                }
            }
        } catch (IOException e) {
            System.err.println("Error starting server: " + e.getMessage());
        }
    }

    private static JSONArray readFavoriteMusicJsonArray() throws IOException {
        String content = new String(Files.readAllBytes(JSON_FILE_PATH), StandardCharsets.UTF_8);
        return (JSONArray) JSONValue.parse(content);
    }
}