Szakkörök‎ > ‎Algoritmus szakkör‎ > ‎2014-2015‎ > ‎

28. alkalom

Az utolsó szakköri órán a beléptetéssel együtt megírt szerverhez készítünk HTML5/jquery alapú klienst.

A szerver pillanatnyilag így néz ki:

package hu.berzsenyi.hb;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import fi.iki.elonen.NanoHTTPD;
import fi.iki.elonen.NanoHTTPD.IHTTPSession;
import fi.iki.elonen.NanoHTTPD.Response;
import fi.iki.elonen.NanoHTTPD.Response.Status;
import java.util.UUID;

public class OneNumberGame extends NanoHTTPD {
    public static class Player {
        String pw;
        int number;
        
        public Player(String pw) {
            this.pw = pw;
            number = -1;
        }
    }
    
    public static void main(String[] args) {
        OneNumberGame server = new OneNumberGame();
        try {
            server.start();
        } catch (IOException ioe) {
            System.err.println("Couldn't start server:\n" + ioe);
            System.exit(-1);
        }

        System.out.println("Server started, Hit Enter to stop.\n");

        try {
            System.in.read();
        } catch (Throwable ignored) {
        }

        server.stop();
        System.out.println("Server stopped.\n");
    }
    
    private final Boolean ONE = true, MORE = false;

    private Map<Integer, Integer> numbers = new HashMap<Integer, Integer>();
    private Map<String, Player> players = new HashMap<String, Player>();
    private boolean running = true;
    private int winnerNumber = -1;
    private String winnerName = null;

    public OneNumberGame() {
        super(12345);
    }

    @Override
    public synchronized Response serve(IHTTPSession session) {
        String uri = session.getUri();
        
        if(uri.equals("/reg")) {
            return register(session.getParms().get("name"));
        } else {
            if (uri.equals("/send")) {
                Map<String, String> parms = session.getParms();
                if(!parms.containsKey("name"))
                    return new Response("No name found!");
                if(!parms.containsKey("pw"))
                    return new Response("No password found!");
                String name = parms.get("name"), pw = parms.get("pw");
                if(!players.get(parms.get("name")).pw.equals(parms.get("pw")))
                    return new Response("Wrong password!");
                if(!parms.containsKey("number"))
                    return new Response("Need parameter called number!");
                String numberStr = parms.get("number");
                try {
                    return send(parms.get("name"), Integer.parseInt(numberStr));
                } catch(Exception e) {
                    e.printStackTrace();
                    return new Response("Error parsing number!");
                }
            }
            else if (uri.equals("/finish"))
                return finish();
            else if (uri.equals("/winner"))
                return winner();
            else if (uri.equals("/clear"))
                return clear();
        }

        return new Response(Status.NOT_FOUND, MIME_PLAINTEXT,
            "Command not found");
    }

    private Response register(String name) {
        if(name == null)
            return new Response("Need a parameter called name!");
        if(players.containsKey(name))
            return new Response("Name is already used!");
        
        String pw = UUID.randomUUID().toString();
        players.put(name, new Player(pw));
        return new Response("Registration succeded! Your password is "+pw);
    }

    private Response send(String playerName, int number) {
        if (!running)
            return new Response(Status.BAD_REQUEST, MIME_PLAINTEXT,
                "The game is not started");
        if(players.get(playerName).number != -1)
            return new Response("You have already guessed!");
        try {
            if (number <= 0)
                return new Response(Status.BAD_REQUEST, MIME_PLAINTEXT,
                    "Number should be positive");
            
            players.get(playerName).number = number;
            numbers.put(number, numbers.containsKey(number) ? numbers.get(number)+1 : 1);

            return new Response(Status.OK, MIME_PLAINTEXT, "Success");

        } catch (NumberFormatException e) {
            return new Response(Status.BAD_REQUEST, MIME_PLAINTEXT,
                "Number should be an integer");
        }
    }

    private Response finish() {
        if (!running)
            return new Response(Status.METHOD_NOT_ALLOWED, MIME_PLAINTEXT,
                "The game is not running");
        running = false;
        winnerNumber = -1;
        for(Integer key : numbers.keySet())
            if(numbers.get(key) == 1 && (winnerNumber == -1 || key < winnerNumber)) {
                winnerNumber = key;
            }
        if(winnerNumber != -1) {
            winnerName = null;
            for(String key : players.keySet())
                if(players.get(key).number == winnerNumber) {
                    winnerName = key;
                    break;
                }
        }
        for(String key : players.keySet())
            players.get(key).number = -1;
        
        return new Response(Status.OK, MIME_PLAINTEXT,
            "The game has been finished :)");
    }

    private Response winner() {
        if (running)
            return new Response(Status.METHOD_NOT_ALLOWED, MIME_PLAINTEXT,
                "The game is running yet");
        
        if (winnerNumber == -1)
            return new Response(Status.OK, MIME_PLAINTEXT, "There is no winner.");
        
        return new Response(Status.OK, MIME_PLAINTEXT, winnerName+" won the game with the number "+winnerNumber);
    }

    private Response clear() {
        running = true;
        numbers.clear();
        return new Response(Status.OK, MIME_PLAINTEXT,
            "A new game has been started :)");
    }
}

A honlap és a szerver közötti HTTP-alapú kommunikációt a jquery javascript könyvtár segítségével valósítjuk meg.

<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.get("http://localhost:12345/send/nev=alma&pw=783f3205-0a5e-48af-bd46-d86dc57942cc&number=".concat($('#v').val()), 
        function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
        });
    });
});
</script>
</head>
<body>
<form><input type="text" id="v" maxlength="6"> </form>
<button>Szám küldése</button>
</body>
</html>