与http请求通信Java-Javascript

时间:2015-03-14 12:29:42

标签: java javascript minecraft bukkit mit-scratch

最近,我一直试图在minecraft服务器(用Java运行)和scratch(用JavaScript运行)之间进行通信。 我已经用java编写了代码:

package me.yotam180;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

import org.bukkit.Bukkit;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;


public class HttpProcessor {
     public MainClass plugin;
    public HttpProcessor (MainClass plug) throws IOException {
        plugin = plug;
        plugin.getLogger().info("CREATED HTTTP PROCESSOR");
        HttpServer server = HttpServer.create(new InetSocketAddress(9090), 0);
        server.createContext("/pollplayer", new PollPlayerHandler());
        server.createContext("/killplayer", new KillPlayerHandler());
        plugin.getLogger().info("STARTED HTTTP SERVER");
        server.setExecutor(null); // creates a default executor
        server.start();
    }

    static class PollPlayerHandler implements HttpHandler {

        @SuppressWarnings("deprecation")
        @Override
        public void handle(HttpExchange httpExchange) throws IOException {
            // TODO Auto-generated method stub
            Map <String,String>parms = HttpProcessor.queryToMap(httpExchange.getRequestURI().getQuery());
            StringBuilder response = new StringBuilder();
            response.append(Bukkit.getPlayer(parms.get("name")).getLocation().toString());
            HttpProcessor.writeResponse(httpExchange, response.toString());
        }
    }
    static class KillPlayerHandler implements HttpHandler {

        @SuppressWarnings("deprecation")
        @Override
        public void handle(HttpExchange httpExchange) throws IOException {
            // TODO Auto-generated method stub
            Map <String,String>parms = HttpProcessor.queryToMap(httpExchange.getRequestURI().getQuery());
            Bukkit.getPlayer(parms.get("name")).setHealth(0);
            HttpProcessor.writeResponse(httpExchange, "SUCCESS");
        }
    }

    public static void writeResponse(HttpExchange httpExchange, String response) throws IOException {
        httpExchange.sendResponseHeaders(200, response.length());
        OutputStream os = httpExchange.getResponseBody();
        os.write(response.getBytes());
        os.close();
      }

    public static Map<String, String> queryToMap(String query){
        Map<String, String> result = new HashMap<String, String>();
        for (String param : query.split("&")) {
            String pair[] = param.split("=");
            if (pair.length>1) {
                result.put(pair[0], pair[1]);
            }else{
                result.put(pair[0], "");
            }
        }
        return result;
      }

}

现在我必须制作一个临时的HTTP客户端。我尝试的每一种方式,它只是没有工作。我尝试打开浏览器,编写http://localhost:9090/pollplayer?name=yotam_salmon并报告我的播放器位置。现在我的问题是刮刮JS。

这是:

new (function () {
    var ext = this;

    // Cleanup function when the extension is unloaded
    ext._shutdown = function () { };

    // Status reporting code
    // Use this to report missing hardware, plugin or unsupported browser
    ext._getStatus = function () {
        return { status: 2, msg: 'Ready' };
    };

    ext.get_Player = function (name, callback) {
        //in this function i need to call http://localhost:9090/pollplayer?name= + name, wait for the response and then callback it.
        //the response can't be "return response;", and it cannot be call backed from another function. If this function was called, it
        //has to report the location back as a string
    };

    // Block and block menu descriptions
    var descriptor = {
        blocks: [
            ['R', 'location of %s', 'get_Player', 'Player'],
        ]
    };

    // Register the extension
    ScratchExtensions.register('ScratchCraft', descriptor, ext);
})();

我不能以不同的方式格式化我的JS代码,因为Scratch只能使用这种格式。(这里解释:http://llk.github.io/scratch-extension-docs/)。在ext.get_Player函数中,我必须转到Java http服务器,请求/pollplayer?name= + name并回调它。

我很乐意得到解决方案:)谢谢!

1 个答案:

答案 0 :(得分:7)

解决方案非常简单。我只需要添加一个#34; Allow-Access-Cross-Origin&#34;的标题,它就解决了。

httpExchange.getResponseHeaders().set("Access-Control-Allow-Origin", "*");
httpExchange.getResponseHeaders().set("Content-Type", "text/plain");