Ir para conteúdo
  • 0

Socket não pega motd personalizado ?


Solitario

Pergunta

Posts Recomendados

@UP

;-; derrepente começou a só dar connection refused .... mesmo com o servidor on

 

 

 

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class Server {
    private boolean online;
    private String motd;


    public String getMotd() {
        return motd;
    }

    public void setMotd(String motd) {
        this.motd = motd;
    }



    public boolean isOnline() {
        return online;
    }

    public void setOnline(boolean online) {
        this.online = online;
    }




    public Server(String host, int port) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Socket socket = null;
                InetAddress addr = null;

                // INSERT hostname here (name or ip)
                String hostname = host;

                //========== Converting hostname to ip ===========
                try {
                    addr = InetAddress.getByName(hostname);
                } catch (UnknownHostException e2) {
                    e2.printStackTrace();
                }

                hostname = addr.getCanonicalHostName();

                //============ Creating Socket ============

                try {
                    socket = new Socket(hostname, port);
                    online = true;
                }catch (IOException e1) {
                    e1.printStackTrace();
                    online = false;
                }
                if(socket == null){
                    return;
                }
                DataOutputStream output = null;
                BufferedReader reader = null;
                StringBuilder str = new StringBuilder();

                try {
                    output = new DataOutputStream(socket.getOutputStream());
                    reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));   // notice the UTF-8 here!

                    // Allocate Buffer with the right amount of bytes
                    ByteBuffer buffer = ByteBuffer.allocate(7 + hostname.length());

                    //========= START Writing Protocol header ========
                    buffer.put((byte) (6 + hostname.length())); // send length of whole packet
                    buffer.put((byte) 0); // send packetID
                    buffer.put((byte) 47); // send protocol Version

                    //========= Start Writing Hostname ===========

                    //Write length of HostName
                    buffer.put((byte) hostname.length());

                    for(int i = 0; i < hostname.length(); i++) {
                        buffer.put((byte) hostname.toCharArray()[i]);
                    }

                    //=============start writing port================
                    int[] portBytes = new int[2];
                    portBytes[0] = (byte) (port & 0xFF);
                    portBytes[1] = (byte) ((port >>> 8) & 0xFF);
                    buffer.put((byte) portBytes[1]);
                    buffer.put((byte) portBytes[0]);


                    //==========Add State==========
                    buffer.put((byte) 1);

                    output.write(buffer.array());

                    output.flush();

                    //=========== Send Request =========
                    buffer = ByteBuffer.allocate(2);
                    buffer.put((byte) 1);
                    buffer.put((byte) 0);

                    output.write(buffer.array());

                    output.flush();

                    int tmpInt;

                    while((tmpInt = reader.read()) != -1 && tmpInt < 65535) {
                        if(str.toString().endsWith("fav")) {
                            break;
                        }
                        str.append((char) tmpInt);
                    }

                    //get Result
                    String result = str.toString(); // get String
                    int descriptionIndex = result.indexOf("\"description\":\"") + 15;    // get MOTD start index
                    int descEndIndex = result.indexOf("\",\"", descriptionIndex);     // get MOTD end index

                    result = result.substring(descriptionIndex, descEndIndex);        // get the MOTD
                    motd = result;
                } catch(StringIndexOutOfBoundsException ex) {
                    // maybe do sth?
                } catch(IOException e) {
                    // do sth
                }
                finally {
                    try {
                        if(reader != null) {
                            reader.close();
                        }
                        if(output != null) {
                            output.close();
                        }
                        if(socket != null) {
                            socket.close();
                        }

                    } catch(IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();


    }
    
} 

 

 

Editado por Solitario
Link para o comentário
Compartilhar em outros sites

@UP

;-; derrepente começou a só dar connection refused .... mesmo com o servidor on

 

 

 

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class Server {
    private boolean online;
    private String motd;


    public String getMotd() {
        return motd;
    }

    public void setMotd(String motd) {
        this.motd = motd;
    }



    public boolean isOnline() {
        return online;
    }

    public void setOnline(boolean online) {
        this.online = online;
    }




    public Server(String host, int port) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Socket socket = null;
                InetAddress addr = null;

                // INSERT hostname here (name or ip)
                String hostname = host;

                //========== Converting hostname to ip ===========
                try {
                    addr = InetAddress.getByName(hostname);
                } catch (UnknownHostException e2) {
                    e2.printStackTrace();
                }

                hostname = addr.getCanonicalHostName();

                //============ Creating Socket ============

                try {
                    socket = new Socket(hostname, port);
                    online = true;
                }catch (IOException e1) {
                    e1.printStackTrace();
                    online = false;
                }
                if(socket == null){
                    return;
                }
                DataOutputStream output = null;
                BufferedReader reader = null;
                StringBuilder str = new StringBuilder();

                try {
                    output = new DataOutputStream(socket.getOutputStream());
                    reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));   // notice the UTF-8 here!

                    // Allocate Buffer with the right amount of bytes
                    ByteBuffer buffer = ByteBuffer.allocate(7 + hostname.length());

                    //========= START Writing Protocol header ========
                    buffer.put((byte) (6 + hostname.length())); // send length of whole packet
                    buffer.put((byte) 0); // send packetID
                    buffer.put((byte) 47); // send protocol Version

                    //========= Start Writing Hostname ===========

                    //Write length of HostName
                    buffer.put((byte) hostname.length());

                    for(int i = 0; i < hostname.length(); i++) {
                        buffer.put((byte) hostname.toCharArray()[i]);
                    }

                    //=============start writing port================
                    int[] portBytes = new int[2];
                    portBytes[0] = (byte) (port & 0xFF);
                    portBytes[1] = (byte) ((port >>> 8) & 0xFF);
                    buffer.put((byte) portBytes[1]);
                    buffer.put((byte) portBytes[0]);


                    //==========Add State==========
                    buffer.put((byte) 1);

                    output.write(buffer.array());

                    output.flush();

                    //=========== Send Request =========
                    buffer = ByteBuffer.allocate(2);
                    buffer.put((byte) 1);
                    buffer.put((byte) 0);

                    output.write(buffer.array());

                    output.flush();

                    int tmpInt;

                    while((tmpInt = reader.read()) != -1 && tmpInt < 65535) {
                        if(str.toString().endsWith("fav")) {
                            break;
                        }
                        str.append((char) tmpInt);
                    }

                    //get Result
                    String result = str.toString(); // get String
                    int descriptionIndex = result.indexOf("\"description\":\"") + 15;    // get MOTD start index
                    int descEndIndex = result.indexOf("\",\"", descriptionIndex);     // get MOTD end index

                    result = result.substring(descriptionIndex, descEndIndex);        // get the MOTD
                    motd = result;
                } catch(StringIndexOutOfBoundsException ex) {
                    // maybe do sth?
                } catch(IOException e) {
                    // do sth
                }
                finally {
                    try {
                        if(reader != null) {
                            reader.close();
                        }
                        if(output != null) {
                            output.close();
                        }
                        if(socket != null) {
                            socket.close();
                        }

                    } catch(IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();


    }
    
} 

 

 

 

Ta bem zuado dessa maneira ;-;

 

Vou ver se faço um com CompletableFuture... vai ficar melhor.

Link para o comentário
Compartilhar em outros sites

Ta bem zuado dessa maneira ;-;

 

Vou ver se faço um com CompletableFuture... vai ficar melhor.

O pior que foi tão sem motivo .-. Ele começou dando os resultado e refused no meu pc achei que o problema seria por tar no meu pc ... porém mandei para a host e foi do mesmo jeito '-' só que sem dar resultado só refused mesmo '-' ...

Link para o comentário
Compartilhar em outros sites

O pior que foi tão sem motivo .-. Ele começou dando os resultado e refused no meu pc achei que o problema seria por tar no meu pc ... porém mandei para a host e foi do mesmo jeito '-' só que sem dar resultado só refused mesmo '-' ...

 

Qual versão do seu sv mesmo? preciso testar.

Link para o comentário
Compartilhar em outros sites

e.e ... manda como você usou e.e

 

Adaptei aquele MinecraftServerPing. Deixei em 1 classe só e adicione CompletableFuture pra rodar async.

 

https://gist.github.com/leonardosnt/dad9d0c75a51f5117326340734fccdbe

 

Como você pode usar:

 

// Isso fica no escopo da classe....
public Result resultDoServer1;
public Result resultDoServer2;


// Você pode colocar em uma task.
// Pode criar um desse pra cada server

ServerQuery q = new ServerQuery("ip do server1", porta do server 1);
q.runQueryAsync()
  .whenComplete((result, err) -> {
    if (err == null) {
      // Sincroniza pra evitar dar merda, pois isso roda em uma Thread separada.
      syncronized (resultDoServer1) {
        resultDoServer1 = result;
      }
    } else {
      // deu erro, printa no console ou sla;
    }
  });
Editado por leonardosc
Link para o comentário
Compartilhar em outros sites

 

 

Adaptei aquele MinecraftServerPing. Deixei em 1 classe só e adicione CompletableFuture pra rodar async.

 

https://gist.github.com/leonardosnt/dad9d0c75a51f5117326340734fccdbe

 

Como você pode usar:

 

// Isso fica no escopo da classe....
public Result resultDoServer1;
public Result resultDoServer2;


// Você pode colocar em uma task.
// Pode criar um desse pra cada server

ServerQuery q = new ServerQuery("ip do server1", porta do server 1);
q.runQueryAsync()
  .whenComplete((result, err) -> {
    if (err == null) {
      // Sincroniza pra evitar dar merda, pois isso roda em uma Thread separada.
      syncronized (resultDoServer1) {
        resultDoServer1 = result;
      }
    } else {
      // deu erro, printa no console ou sla;
    }
  });

bvk1sip.png

Link para o comentário
Compartilhar em outros sites

bvk1sip.png

 

'-'-'-'-'-'-'-''-'-'-'-'-'-'-'-'-'-'-'-'-'-'-'

 

Adiciona o spigot/craftbukkit (o jar do server) como dependência.

 

E muda pra org.json.simple.JSONObject

Editado por leonardosc
Link para o comentário
Compartilhar em outros sites

Editei o post...

 

E muda pra org.json.simple.JSONObject

FyOJAMp.png

 

 

FyOJAMp.png

 

oBFyVTe.png

 

@Edit

Também queria saber qual import devo usar se é o da class para o Result '-'

Editado por Solitario
Link para o comentário
Compartilhar em outros sites

'-' ... não tinha ... agora tenho '-' só não sei usar

 

Muda o final pra isso:

JSONObject obj = (JSONObject) new JSONParser().parse(json);
JSONObject players = (JSONObject) obj.get("players");

int onlinePlayers = ((Long) players.get("online")).intValue();
String motd = (String) obj.get("description");

return new Result(onlinePlayers, motd);

Me adiciona: leonardosnt#4963

Link para o comentário
Compartilhar em outros sites

Visitante
Este tópico está impedido de receber novos posts.
×
×
  • Criar Novo...