PHP to Java Connection

2019-07-19 12:42发布

问题:

I am working on a project where I send supposedly press a button on a webpage and it then executes a command in java. What I'm looking for is something like this. Say if I pressed a button and then it sends a command to the minecraft server to reload plugins. How would I go achieving this? Thanks

回答1:

When you have to comunicate between different applications you will problably need a bridge. In your case I'd suggest to use Minecraft's RCON service (must be enabled in the confingiration) or a plugin that do something similar, like Websend.

Websend code is actually available on Github if you would like to know how the plugin work.



回答2:

Connection between PHP and Java through sockets

Step 1:

Create a java server

I have created a nice API for these situations. you can use them if you would like:

ChatServer

all you need to do is create a new instance of this class

package com.weebly.foxgenesis.src;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.io.*;

public final class ChatServer implements Runnable 
{  
    private final int CLIENTMAXIMUM;
    private ChatServerThread clients[];
    private ServerSocket server = null;
    private Thread       thread = null;
    private int clientCount = 0;
    private final ServerReciever output;
    private List<ConnectHandler> connectHandlers = new ArrayList<ConnectHandler>();
    private List<QuitHandler> quitHandlers = new ArrayList<QuitHandler>();

    /**
     * creates a new ChatServer for connection between clients
     * @param a ServerReciever implementing class
     */
    public ChatServer(ServerReciever a)
    {  
        CLIENTMAXIMUM = a.getMaximunClients();
        output = a;
        clients = new ChatServerThread[CLIENTMAXIMUM];
        try
        {  
            server = new ServerSocket();
            server.bind(new InetSocketAddress(output.getHost(), output.getPort()));
            log(server);
            start(); 
        }
        catch(IOException ioe)
        {  
            error("Can not bind to port " + a.getPort() + ": " + ioe.getMessage()); 
        }
    }

    /**
     * Force the Server to handle a msg
     */
    public void add(String text)
    {
        output.handle(text);
    }

    /**
     * Force the Server to handle an error
     */
    public void error(String text)
    {
        output.handleError(text);
    }

    /**
     * Log to the server
     */
    public void log(Object text)
    {
        output.handleLog(text);
    }

    /**
     * send a message to a specific client
     * @param ID ID of client
     * @param msg
     */
    public void send(int ID, String msg)
    {
        clients[findClient(ID)].send(msg);
        add(msg);
    }


    /**
     * Called by runnable
     */
    public void run()
    { 
        while (thread != null)
        {  
            try
            {   
                if(clientCount != CLIENTMAXIMUM){
                    log("Waiting for a client ..."); 
                    addThread(server.accept()); 
                }
            }
            catch(IOException ioe)
            {  
                error("Server accept error: " + ioe); 
                stop(); 
            }
        }

    }

    private void start()  
    { 
        if (thread == null)
        {  
            thread = new Thread(this); 
            thread.start();
        }
    }

    /**
     * Stops the server 
     */
    @SuppressWarnings("deprecation")
    public void stop()   
    { 
        if (thread != null)
        { 
            thread.stop(); 
            thread = null;
        }
    }

    private int findClient(int ID)
    {  
        for (int i = 0; i < clientCount; i++)
            if (clients[i].getID() == ID)
                return i;
        return -1;
    }

    /**
     * sends a message to a 
     * @param ID
     * @param input
     */
    public synchronized void handle(int ID, String input)
    {  
        StringTokenizer t = new StringTokenizer(input);
        String[] arg = new String[t.countTokens()];
        for(int i=0; t.hasMoreElements(); i++)
            arg[i] = t.nextToken(",");
        if(arg[0] == "new")
            switch(input)
            {
            case".bye":
            {
                clients[findClient(ID)].send(".bye");
                remove(ID); 
                break;
            }
            default:
            {
                for (int i = 0; i < clientCount; i++)
                    clients[i].send(input); 
                break;
            }
            }
    }
    /**
     * sends a message to all clients
     * @param input message to send
     */
    public void sendAll(String input)
    {
        for (int i = 0; i < clientCount; i++)
            clients[i].send(input); 
    }

    /**
     * remove a selected ID
     * @param ID ID of client
     */
    @SuppressWarnings("deprecation")
    public synchronized void remove(int ID)
    {  
        int pos = findClient(ID);
        if (pos >= 0)
        {  
            ChatServerThread toTerminate = clients[pos];
            log("Removing client thread " + ID + " at " + pos);
            if (pos < clientCount-1)
                for (int i = pos+1; i < clientCount; i++)
                    clients[i-1] = clients[i];
            clientCount--;
            QuitEvent e = new QuitEvent(toTerminate.getID());
            e.setGameBreaking(true);
            for(QuitHandler a: quitHandlers)
                a.quit(e);
            try
            {  
                toTerminate.close(); }
            catch(IOException ioe)
            {  
                error("Error closing thread: " + ioe); 
            }
            toTerminate.stop(); 
        }
    }

    private void addThread(Socket socket)
    {  
        if (clientCount < clients.length)
        { 
            log("Client accepted: " + socket);
            clients[clientCount] = new ChatServerThread(this, socket);
            try
            { 
                clients[clientCount].open(); 
                clients[clientCount].start();  
                ClientConnectEvent e = new ClientConnectEvent(clients[clientCount],clients[clientCount].getID());
                clientCount++; 
                for(ConnectHandler a: connectHandlers)
                    a.connect(e);
            }
            catch(IOException ioe)
            {  
                error("Error opening thread: " + ioe); 
            }
        }
        else
            error("Client refused: maximum " + clients.length + " reached.");
    }

    public String toString()
    {
        return "ChatServer{;host=" + output.getHost() + ";port=" + output.getPort() + ";clients=" + clientCount + ";}";
    }

    public int getAmountOfClients()
    {
        return clientCount;
    }

    public void addConnectHandler(ConnectHandler handler)
    {
        connectHandlers.add(handler);
    }

    public void removeConnectHandler(ConnectHandler handler)
    {
        connectHandlers.remove(handler);
    }

    public int getMaxClients()
    {
        return CLIENTMAXIMUM;
    }

    public void addQuitHandler(QuitHandler quitHandler) 
    {
        quitHandlers.add(quitHandler);
    }
    public void removeQuitHandler(QuitHandler quithandler)
    {
       quitHandlers.remove(quithandler);
    }
}

ChatServerThread

Used by the ChatServer as client connections

package com.weebly.foxgenesis.src;
import java.net.*;
import java.io.*;

public final class ChatServerThread extends Thread
{  
    private ChatServer server = null;
    private Socket socket = null;
    private int ID = -1;
    private DataInputStream  streamIn  =  null;
    private DataOutputStream streamOut = null;

    public ChatServerThread(ChatServer server, Socket socket)
    {  
        super();
        this.server = server;
        this.socket = socket;
        this.ID = socket.getPort();
    }
    @SuppressWarnings("deprecation")
    public void send(String msg)
    {   
        try
        {  
            streamOut.writeUTF(msg);
            streamOut.flush();
        }
        catch(IOException ioe)
        {  
            server.error(ID + " ERROR sending: " + ioe.getMessage());
            server.remove(ID);
            stop();
        }
    }

    public int getID()
    { 
        return ID;
    }

    @SuppressWarnings("deprecation")
    @Override
    public void run()
    {  
        server.log("Server Thread " + ID + " running.");
        while (true)
        {  
            try
            {  
                server.handle(ID, streamIn.readUTF());
            }
            catch(IOException ioe)
            {  
                server.error(ID + " ERROR reading: " + ioe.getMessage());
                server.remove(ID);
                stop();
            }
        }
    }

    public void open() throws IOException
    {  
        streamIn = new DataInputStream(new 
                BufferedInputStream(socket.getInputStream()));
        streamOut = new DataOutputStream(new
                BufferedOutputStream(socket.getOutputStream()));
    }

    public void close() throws IOException
    {  
        if (socket != null)    socket.close();
        if (streamIn != null)  streamIn.close();
        if (streamOut != null) streamOut.close();
    }
}

ClientConnectEvent

package com.weebly.foxgenesis.src;

public class ClientConnectEvent extends ConnectionEvent
{
    private final ChatServerThread client;

    public ClientConnectEvent(ChatServerThread client, int clientID)
    {
        super(clientID);
        this.client = client;
    }

    public ChatServerThread getClient()
    {
        return client;
    }

    @Override
    public boolean isConnectionBreaking(){return false;}
}

ConnectHandler

package com.weebly.foxgenesis.src;

public interface ConnectHandler 
{
    public void connect(ClientConnectEvent e);
}

ClientQuitEvent

package com.weebly.foxgenesis.src;

public class ClientQuitEvent extends ConnectionEvent
{
    public ClientQuitEvent(int clientID)
    {
        super(clientID);
    }

    @Override
    public boolean isConnectionBreaking() 
    {
        return true;
    }
}

QuitHandler

package com.weebly.foxgenesis.src;

public interface QuitHandler 
{
    public void quit(ClientQuitEvent e);
}

ServerReciever

package com.weebly.foxgenesis.src;

public interface ServerReciever 
{
    public void handle(String msg);
    public void handleError(String msg);
    public int getPort();
    public int getMaximunClients();
    public void handleLog(Object text);
    public String getHost();
}

ConnectionEvent

package com.weebly.foxgenesis.src;

public abstract class ConnectionEvent 
{
    public abstract boolean isConnectionBreaking();
    private int clientID;
    public ConnectionEvent(int clientID)
    {
        this.clientID = clientID;
    }

    public int getClientID()
    {
        return clientID;
    }
}

Step 2:

Connect Server to Bukkit

i have provided an example on how to connect the server to bukkit by making a new plugin.

public class MyPlugin extends JavaPlugin
{
     @Override
     public void onEnable()
     {
        ChatServer server = new ChatServer(new ServerReciever()
        {
            @Override
            public void handle(String msg){handleMsg(msg);}

            @Override
            public void handleError(String msg){handleErr(msg);}

            @Override
            public int getPort(){return 25567}

            @Override
            public int getMaximunClients(){return 100;}

            @Override
            public void handleLog(Object text){log(text);}

            @Override
            public String getHost(){return "localhost";}
        }
   }
   public void handleLog(Object text)
   {
      System.out.println(text);
   }
   public void handelErr(String msg)
   {
     System.err.println(msg);
   }
   public void handleMsg(String msg)
   {
     if(msg.equalsIgnoreCase("reload"))
           Bukkit.reloadOrSomething(); //i don't know the void off the top of my head
   }
}

Step 3:

Port Forward

if you don't know what that is go ahead and google it. there are some great tutorials online. you want to port forward the port that you set in the code.

Step 4:

Send a message to the Server

i do not know PHP but all you need to do is send a UTF-8 Encoded message to the server's ip on the port that you hard coded above.

Step 5:

ENJOY!