Ir para conteúdo
  • 0

Socket não pega motd personalizado ?


Solitario

Pergunta

Posts Recomendados

Sem saber que código que você usou fica difícil ajudar.

API

 

package me.arthurgui.hub.api;


import me.arthurgui.hub.main;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset;

public class ServerPing {

    private static String address;
    private static int port;
    private static int timeout;

    private static boolean online;
    private static int playercount;
    private static int maxplayers;
    private static String motd;

    public static void Server(String address, int port, int timeout){
        ServerPing.address = address;
        ServerPing.port = port;
        ServerPing.timeout = timeout;
    }

    public static String getAddress(){
        return ServerPing.address;
    }

    public static void setAddress(String address){
        ServerPing.address = address;
    }

    public static int getPort(){
        return ServerPing.port;
    }

    public static void setPort(int port){
        ServerPing.port = port;
    }

    public static int getTimeout(){
        return ServerPing.timeout;
    }

    public static void setTimeout(int timeout){
        ServerPing.timeout = timeout;
    }

    public static boolean isOnline(){
        return ServerPing.online;
    }

    private static void setOnline(boolean online){
        ServerPing.online = online;
    }

    public static int getPlayerCount(){
        return ServerPing.playercount;
    }

    private static void setPlayerCount(int playercount){
        ServerPing.playercount = playercount;
    }

    public static int getMaxPlayers(){
        return ServerPing.maxplayers;
    }

    private static void setMaxPlayers(int maxplayers){
        ServerPing.maxplayers = maxplayers;
    }

    public static String getMotd(){
        return ServerPing.motd;
    }

    private static void setMotd(String motd){
        ServerPing.motd = motd;
    }

    public static void connect(){
        try{
            Socket socket = new Socket();
            socket.setTcpNoDelay(true);
            socket.connect(new InetSocketAddress(ServerPing.getAddress(), ServerPing.getPort()), ServerPing.getTimeout());
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            dos.write(0xFE);
            int data = dis.read();
            setOnline(true);
            socket.close();
        }catch(SocketTimeoutException e){
            main.instance.getServer().getConsoleSender().sendMessage("[ServerStatus] Connection timed out.");
            setOnline(false);
        }catch(IOException e){
            setOnline(false);
        }
    }

    public static void ping(){
        try{
            Socket socket = new Socket();
            OutputStream outputStream;
            DataOutputStream dataOutputStream;
            InputStream inputStream;
            InputStreamReader inputStreamReader;
            socket.connect(new InetSocketAddress(ServerPing.getAddress(), ServerPing.getPort()), ServerPing.getTimeout());
            outputStream = socket.getOutputStream();
            dataOutputStream = new DataOutputStream(outputStream);
            inputStream = socket.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-16BE"));
            dataOutputStream.write(new byte[]{(byte) 0xFE,(byte) 0x01});
            int packetId = inputStream.read();
            ServerPing.setOnline(true);
            if(packetId == -1){
                dataOutputStream.close();
                outputStream.close();
                inputStreamReader.close();
                inputStream.close();
                socket.close();
                throw new IOException("Premature end of stream.");
            }
            if(packetId != 0xFF){
                dataOutputStream.close();
                outputStream.close();
                inputStreamReader.close();
                inputStream.close();
                socket.close();
                throw new IOException("Invalid packet ID (" + packetId + ").");
            }
            int length = inputStreamReader.read();
            if(length == -1){
                dataOutputStream.close();
                outputStream.close();
                inputStreamReader.close();
                inputStream.close();
                socket.close();
                throw new IOException("Premature end of stream.");
            }
            if(length == 0){
                dataOutputStream.close();
                outputStream.close();
                inputStreamReader.close();
                inputStream.close();
                socket.close();
                throw new IOException("Invalid string length.");
            }
            char[] chars = new char[length];
            if(inputStreamReader.read(chars,0,length) != length){
                dataOutputStream.close();
                outputStream.close();
                inputStreamReader.close();
                inputStream.close();
                socket.close();
                throw new IOException("Premature end of stream.");
            }
            String string = new String(chars);
            if(string.startsWith("§")){
                String[] data = string.split("\0");
                ServerPing.setMotd(data[3]);
                ServerPing.setPlayerCount(Integer.parseInt(data[4]));
                ServerPing.setMaxPlayers(Integer.parseInt(data[5]));
            }else{
                String[] data = string.split("§");
                ServerPing.setMotd(data[0]);
                ServerPing.setPlayerCount(Integer.parseInt(data[1]));
                ServerPing.setMaxPlayers(Integer.parseInt(data[2]));
            }
            dataOutputStream.close();
            outputStream.close();
            inputStreamReader.close();
            inputStream.close();
            socket.close();
        } catch (SocketException exception) {
            ServerPing.setOnline(false);
        } catch (IOException exception) {
            ServerPing.setOnline(false);
        }
    }
} 

 

 

ServerPing sp = new ServerPing();
sp.Server("127.0.0.1", 25566, 7000);
sp.ping();
if (sp.isOnline()) {
	Bukkit.broadcastMessage("ONLINE! " + sp.getMotd() + " " + sp.getMaxPlayers() + " " + sp.getPlayerCount());
}
Link para o comentário
Compartilhar em outros sites

 

API

 

package me.arthurgui.hub.api;


import me.arthurgui.hub.main;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset;

public class ServerPing {

    private static String address;
    private static int port;
    private static int timeout;

    private static boolean online;
    private static int playercount;
    private static int maxplayers;
    private static String motd;

    public static void Server(String address, int port, int timeout){
        ServerPing.address = address;
        ServerPing.port = port;
        ServerPing.timeout = timeout;
    }

    public static String getAddress(){
        return ServerPing.address;
    }

    public static void setAddress(String address){
        ServerPing.address = address;
    }

    public static int getPort(){
        return ServerPing.port;
    }

    public static void setPort(int port){
        ServerPing.port = port;
    }

    public static int getTimeout(){
        return ServerPing.timeout;
    }

    public static void setTimeout(int timeout){
        ServerPing.timeout = timeout;
    }

    public static boolean isOnline(){
        return ServerPing.online;
    }

    private static void setOnline(boolean online){
        ServerPing.online = online;
    }

    public static int getPlayerCount(){
        return ServerPing.playercount;
    }

    private static void setPlayerCount(int playercount){
        ServerPing.playercount = playercount;
    }

    public static int getMaxPlayers(){
        return ServerPing.maxplayers;
    }

    private static void setMaxPlayers(int maxplayers){
        ServerPing.maxplayers = maxplayers;
    }

    public static String getMotd(){
        return ServerPing.motd;
    }

    private static void setMotd(String motd){
        ServerPing.motd = motd;
    }

    public static void connect(){
        try{
            Socket socket = new Socket();
            socket.setTcpNoDelay(true);
            socket.connect(new InetSocketAddress(ServerPing.getAddress(), ServerPing.getPort()), ServerPing.getTimeout());
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            dos.write(0xFE);
            int data = dis.read();
            setOnline(true);
            socket.close();
        }catch(SocketTimeoutException e){
            main.instance.getServer().getConsoleSender().sendMessage("[ServerStatus] Connection timed out.");
            setOnline(false);
        }catch(IOException e){
            setOnline(false);
        }
    }

    public static void ping(){
        try{
            Socket socket = new Socket();
            OutputStream outputStream;
            DataOutputStream dataOutputStream;
            InputStream inputStream;
            InputStreamReader inputStreamReader;
            socket.connect(new InetSocketAddress(ServerPing.getAddress(), ServerPing.getPort()), ServerPing.getTimeout());
            outputStream = socket.getOutputStream();
            dataOutputStream = new DataOutputStream(outputStream);
            inputStream = socket.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-16BE"));
            dataOutputStream.write(new byte[]{(byte) 0xFE,(byte) 0x01});
            int packetId = inputStream.read();
            ServerPing.setOnline(true);
            if(packetId == -1){
                dataOutputStream.close();
                outputStream.close();
                inputStreamReader.close();
                inputStream.close();
                socket.close();
                throw new IOException("Premature end of stream.");
            }
            if(packetId != 0xFF){
                dataOutputStream.close();
                outputStream.close();
                inputStreamReader.close();
                inputStream.close();
                socket.close();
                throw new IOException("Invalid packet ID (" + packetId + ").");
            }
            int length = inputStreamReader.read();
            if(length == -1){
                dataOutputStream.close();
                outputStream.close();
                inputStreamReader.close();
                inputStream.close();
                socket.close();
                throw new IOException("Premature end of stream.");
            }
            if(length == 0){
                dataOutputStream.close();
                outputStream.close();
                inputStreamReader.close();
                inputStream.close();
                socket.close();
                throw new IOException("Invalid string length.");
            }
            char[] chars = new char[length];
            if(inputStreamReader.read(chars,0,length) != length){
                dataOutputStream.close();
                outputStream.close();
                inputStreamReader.close();
                inputStream.close();
                socket.close();
                throw new IOException("Premature end of stream.");
            }
            String string = new String(chars);
            if(string.startsWith("§")){
                String[] data = string.split("\0");
                ServerPing.setMotd(data[3]);
                ServerPing.setPlayerCount(Integer.parseInt(data[4]));
                ServerPing.setMaxPlayers(Integer.parseInt(data[5]));
            }else{
                String[] data = string.split("§");
                ServerPing.setMotd(data[0]);
                ServerPing.setPlayerCount(Integer.parseInt(data[1]));
                ServerPing.setMaxPlayers(Integer.parseInt(data[2]));
            }
            dataOutputStream.close();
            outputStream.close();
            inputStreamReader.close();
            inputStream.close();
            socket.close();
        } catch (SocketException exception) {
            ServerPing.setOnline(false);
        } catch (IOException exception) {
            ServerPing.setOnline(false);
        }
    }
} 

 

 

ServerPing sp = new ServerPing();
sp.Server("127.0.0.1", 25566, 7000);
sp.ping();
if (sp.isOnline()) {
	Bukkit.broadcastMessage("ONLINE! " + sp.getMotd() + " " + sp.getMaxPlayers() + " " + sp.getPlayerCount());
}

 

Qual versão do seu servidor?

Link para o comentário
Compartilhar em outros sites

 

Se você executar em uma Thread separada, não.

'-' Creio que ao demorar responder o servidor termina crashando/lagando o lobby .-.

(Não sei se tem um metodo mais facil que possa ficar mandado dados para um servidor) (To fazendo por motd por que é o que mais fica atualizando rapido e sem necessidade de players on)

 

@edit

Notei que deixa o servidor que esta pegando o motd muito lagado

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

Sockets nao é mt leve e seguro, ja vou te dizendo, tds as vezes que usei Socket o servidor Lobby ficava lagado.

Uma alternativa é vc Redis que é um Cache MT FODA e mt rapido, mas se vc nao tem um dedicado para instalar ele ta usando uma host que nao tenha suporte a ele vc pode usar por MySQL que tbm é uma Boa, eu usava, nunca deu lag(pq o select no MySQL é RAPIDO, só o insert que é um problema mas, 1 insert por servidor se tiver 20 servidores nao vai gerar problema pq normalmente a host sua tem SSD)

MySQL para servidor piqueno resolve esse problema de LAG no Lobby e vc consegue adicionar muita mais coisinhas...

Link para o comentário
Compartilhar em outros sites

'-' Creio que ao demorar responder o servidor termina crashando/lagando o lobby .-.

(Não sei se tem um metodo mais facil que possa ficar mandado dados para um servidor) (To fazendo por motd por que é o que mais fica atualizando rapido e sem necessidade de players on)

 

@edit

Notei que deixa o servidor que esta pegando o motd muito lagado

 

Se você rodar na Thread principal é obvio que vai dar lag, o Socket vai bloquear até receber a resposta do servidor.

 

Faz o que eu disse, roda em uma Thread separada.

Link para o comentário
Compartilhar em outros sites

Se você rodar na Thread principal é obvio que vai dar lag, o Socket vai bloquear até receber a resposta do servidor.

 

Faz o que eu disse, roda em uma Thread separada.

new Thread(){
			public void run(){
				getMotd Status = new getMotd();
				Status.Sv(ip1, 25566);
				if(Status.estaOnline()){
					String[] motd = Status.obterMotd().split(";");
					if(motd[0].equalsIgnoreCase("Carregando")){
						hg1 = "§eCarregando";
						hg1t = "§e--";
						hg1o = "§e--";
					}
					if(motd[0].equalsIgnoreCase("Aguardando")){
						hg1 = "§aAguardando para o torneio";
						hg1t = "§e" + motd[1];
						hg1o = "§e" + motd[2];
					}
					if(motd[0].equalsIgnoreCase("Invencibilidade")){
						hg1 = "§eEm Invencibilidade";
						hg1t = "§e" + motd[1];
						hg1o = "§e" + motd[2];
					}
					if(motd[0].equalsIgnoreCase("Iniciado")){
						hg1 = "§cEm Jogo";
						hg1t = "§e" + motd[1];
						hg1o = "§e" + motd[2];
					}
				} else {
					hg1 = "§eOffline";
					hg1t = "§c--";
					hg1o = "§c--";
				}
			}
		}.start();

'-' não é assim ?

 

 

Sockets nao é mt leve e seguro, ja vou te dizendo, tds as vezes que usei Socket o servidor Lobby ficava lagado.

Uma alternativa é vc Redis que é um Cache MT FODA e mt rapido, mas se vc nao tem um dedicado para instalar ele ta usando uma host que nao tenha suporte a ele vc pode usar por MySQL que tbm é uma Boa, eu usava, nunca deu lag(pq o select no MySQL é RAPIDO, só o insert que é um problema mas, 1 insert por servidor se tiver 20 servidores nao vai gerar problema pq normalmente a host sua tem SSD)

MySQL para servidor piqueno resolve esse problema de LAG no Lobby e vc consegue adicionar muita mais coisinhas...

Irei considerar o do MySQL se continuar dando ruim via sockets '-'

Link para o comentário
Compartilhar em outros sites

new Thread(){
			public void run(){
				getMotd Status = new getMotd();
				Status.Sv(ip1, 25566);
				if(Status.estaOnline()){
					String[] motd = Status.obterMotd().split(";");
					if(motd[0].equalsIgnoreCase("Carregando")){
						hg1 = "§eCarregando";
						hg1t = "§e--";
						hg1o = "§e--";
					}
					if(motd[0].equalsIgnoreCase("Aguardando")){
						hg1 = "§aAguardando para o torneio";
						hg1t = "§e" + motd[1];
						hg1o = "§e" + motd[2];
					}
					if(motd[0].equalsIgnoreCase("Invencibilidade")){
						hg1 = "§eEm Invencibilidade";
						hg1t = "§e" + motd[1];
						hg1o = "§e" + motd[2];
					}
					if(motd[0].equalsIgnoreCase("Iniciado")){
						hg1 = "§cEm Jogo";
						hg1t = "§e" + motd[1];
						hg1o = "§e" + motd[2];
					}
				} else {
					hg1 = "§eOffline";
					hg1t = "§c--";
					hg1o = "§c--";
				}
			}
		}.start();

'-' não é assim ?

 

 

Irei considerar o do MySQL se continuar dando ruim via sockets '-'

 

 

Você testou?

Link para o comentário
Compartilhar em outros sites

é o code que estou usando e esta gerando lagg no servidor que tou dando ping e ainda por cima até não receber resposta ele mantem o servidor congelado '-'

 

Manda o código desse "getMotd ".

 

Vou sair agora. Amanha eu vejo.

Link para o comentário
Compartilhar em outros sites

Manda o código desse "getMotd ".

 

Vou sair agora. Amanha eu vejo.

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 getMotd {
    private static String motd;
    private static boolean online;

    public String obterMotd(){
        if(getMotd.motd != null){
            return getMotd.motd;
        }
        return "";
    }

    public boolean estaOnline(){
        return getMotd.online;
    }

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

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

    public void Sv(String host, int port) {
                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);
                    setOnline(true);
                }catch (IOException e1) {
                    setOnline(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
                    setMotd(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();
                    }
                }

    }
}


Sobre o ping dar lagg ... errei é o proprio sv msm que ta horrivel ... 

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

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 getMotd {
    private static String motd;
    private static boolean online;

    public String obterMotd(){
        if(getMotd.motd != null){
            return getMotd.motd;
        }
        return "";
    }

    public boolean estaOnline(){
        return getMotd.online;
    }

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

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

    public void Sv(String host, int port) {
                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);
                    setOnline(true);
                }catch (IOException e1) {
                    setOnline(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
                    setMotd(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();
                    }
                }

    }
}


Sobre o ping dar lagg ... errei é o proprio sv msm que ta horrivel ... 

 

public void Sv(final String host, final int port) {
          new Thread(new Runnable() {
                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);
                    setOnline(true);
                }catch (IOException e1) {
                    setOnline(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
                    setMotd(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();
    }

Tenta assim

Link para o comentário
Compartilhar em outros sites

public void Sv(final String host, final int port) {
          new Thread(new Runnable() {
                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);
                    setOnline(true);
                }catch (IOException e1) {
                    setOnline(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
                    setMotd(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();
    }

Tenta assim

 

Funcionou desse jeito (Esse tipo de thread)

 

--------------------------------------------------------

Só tem um problema ... por que não consigo fazer individual ... tipo tentei assim:

				getMotd Status = new getMotd();
				Status.Sv(ip1, 25566);
				if (Status.estaOnline()) {
					String[] motd = Status.obterMotd().split(";");
					if (motd[0].equalsIgnoreCase("Carregando")) {
						hg1 = "§eCarregando";
						hg1t = "§e--";
						hg1o = "§e--";
					}
					if (motd[0].equalsIgnoreCase("Aguardando")) {
						hg1 = "§aAguardando para o torneio";
						hg1t = "§e" + motd[1];
						hg1o = "§e" + motd[2];
					}
					if (motd[0].equalsIgnoreCase("Invencibilidade")) {
						hg1 = "§eEm Invencibilidade";
						hg1t = "§e" + motd[1];
						hg1o = "§e" + motd[2];
					}
					if (motd[0].equalsIgnoreCase("Andamento")) {
						hg1 = "§cEm Jogo";
						hg1t = "§e" + motd[1];
						hg1o = "§e" + motd[2];
					}
					if (motd[0].equalsIgnoreCase("Finalizado")) {
						hg1 = "§6" + motd[1] + " Venceu!";
						hg1t = "§e--";
						hg1o = "§e--";
					}
				} else {
					hg1 = "§eOffline";
					hg1t = "§c--";
					hg1o = "§c--";
				}


		getMotd Status2 = new getMotd();
		Status2 = new getMotd();
		Status2.Sv(ip2, 25567);
		if (Status2.estaOnline()) {
			String[] motd = Status2.obterMotd().split(";");
			if (motd[0].equalsIgnoreCase("Carregando")) {
				hg2 = "§eCarregando";
				hg2t = "§e--";
				hg2o = "§e--";
			}
			if (motd[0].equalsIgnoreCase("Aguardando")) {
				hg2 = "§aAguardando para o torneio";
				hg2t = "§e" + motd[1];
				hg2o = "§e" + motd[2];
			}
			if (motd[0].equalsIgnoreCase("Invencibilidade")) {
				hg2 = "§eEm Invencibilidade";
				hg2t = "§e" + motd[1];
				hg2o = "§e" + motd[2];
			}
			if (motd[0].equalsIgnoreCase("Andamento")) {
				hg2 = "§cEm Jogo";
				hg2t = "§e" + motd[1];
				hg2o = "§e" + motd[2];
			}
			if (motd[0].equalsIgnoreCase("Finalizado")) {
				hg2 = "§6" + motd[1] + " Venceu!";
				hg2t = "§e--";
				hg2o = "§e--";
			}
		} else {
			hg2 = "§eOffline";
			hg2t = "§c--";
			hg2o = "§c--";
		}

		getMotd Status3 = new getMotd();
		Status3.Sv(ip3, 25568);
		if (Status3.estaOnline()) {
			String[] motd = Status3.obterMotd().split(";");
			if (motd[0].equalsIgnoreCase("Carregando")) {
				hg3 = "§eCarregando";
				hg3t = "§e--";
				hg3o = "§e--";
			}
			if (motd[0].equalsIgnoreCase("Aguardando")) {
				hg3 = "§aAguardando para o torneio";
				hg3t = "§e" + motd[1];
				hg3o = "§e" + motd[2];
			}
			if (motd[0].equalsIgnoreCase("Invencibilidade")) {
				hg3 = "§eEm Invencibilidade";
				hg3t = "§e" + motd[1];
				hg3o = "§e" + motd[2];
			}
			if (motd[0].equalsIgnoreCase("Andamento")) {
				hg3 = "§cEm Jogo";
				hg3t = "§e" + motd[1];
				hg3o = "§e" + motd[2];
			}
			if (motd[0].equalsIgnoreCase("Finalizado")) {
				hg3 = "§6" + motd[1] + " Venceu!";
				hg3t = "§e--";
				hg3o = "§e--";
			}
		} else {
			hg3 = "§eOffline";
			hg3t = "§c--";
			hg3o = "§c--";
		}

Só que todos ficam voltando offline '-'

Link para o comentário
Compartilhar em outros sites

Funcionou desse jeito (Esse tipo de thread)

 

--------------------------------------------------------

Só tem um problema ... por que não consigo fazer individual ... tipo tentei assim:

				getMotd Status = new getMotd();
				Status.Sv(ip1, 25566);
				if (Status.estaOnline()) {
					String[] motd = Status.obterMotd().split(";");
					if (motd[0].equalsIgnoreCase("Carregando")) {
						hg1 = "§eCarregando";
						hg1t = "§e--";
						hg1o = "§e--";
					}
					if (motd[0].equalsIgnoreCase("Aguardando")) {
						hg1 = "§aAguardando para o torneio";
						hg1t = "§e" + motd[1];
						hg1o = "§e" + motd[2];
					}
					if (motd[0].equalsIgnoreCase("Invencibilidade")) {
						hg1 = "§eEm Invencibilidade";
						hg1t = "§e" + motd[1];
						hg1o = "§e" + motd[2];
					}
					if (motd[0].equalsIgnoreCase("Andamento")) {
						hg1 = "§cEm Jogo";
						hg1t = "§e" + motd[1];
						hg1o = "§e" + motd[2];
					}
					if (motd[0].equalsIgnoreCase("Finalizado")) {
						hg1 = "§6" + motd[1] + " Venceu!";
						hg1t = "§e--";
						hg1o = "§e--";
					}
				} else {
					hg1 = "§eOffline";
					hg1t = "§c--";
					hg1o = "§c--";
				}


		getMotd Status2 = new getMotd();
		Status2 = new getMotd();
		Status2.Sv(ip2, 25567);
		if (Status2.estaOnline()) {
			String[] motd = Status2.obterMotd().split(";");
			if (motd[0].equalsIgnoreCase("Carregando")) {
				hg2 = "§eCarregando";
				hg2t = "§e--";
				hg2o = "§e--";
			}
			if (motd[0].equalsIgnoreCase("Aguardando")) {
				hg2 = "§aAguardando para o torneio";
				hg2t = "§e" + motd[1];
				hg2o = "§e" + motd[2];
			}
			if (motd[0].equalsIgnoreCase("Invencibilidade")) {
				hg2 = "§eEm Invencibilidade";
				hg2t = "§e" + motd[1];
				hg2o = "§e" + motd[2];
			}
			if (motd[0].equalsIgnoreCase("Andamento")) {
				hg2 = "§cEm Jogo";
				hg2t = "§e" + motd[1];
				hg2o = "§e" + motd[2];
			}
			if (motd[0].equalsIgnoreCase("Finalizado")) {
				hg2 = "§6" + motd[1] + " Venceu!";
				hg2t = "§e--";
				hg2o = "§e--";
			}
		} else {
			hg2 = "§eOffline";
			hg2t = "§c--";
			hg2o = "§c--";
		}

		getMotd Status3 = new getMotd();
		Status3.Sv(ip3, 25568);
		if (Status3.estaOnline()) {
			String[] motd = Status3.obterMotd().split(";");
			if (motd[0].equalsIgnoreCase("Carregando")) {
				hg3 = "§eCarregando";
				hg3t = "§e--";
				hg3o = "§e--";
			}
			if (motd[0].equalsIgnoreCase("Aguardando")) {
				hg3 = "§aAguardando para o torneio";
				hg3t = "§e" + motd[1];
				hg3o = "§e" + motd[2];
			}
			if (motd[0].equalsIgnoreCase("Invencibilidade")) {
				hg3 = "§eEm Invencibilidade";
				hg3t = "§e" + motd[1];
				hg3o = "§e" + motd[2];
			}
			if (motd[0].equalsIgnoreCase("Andamento")) {
				hg3 = "§cEm Jogo";
				hg3t = "§e" + motd[1];
				hg3o = "§e" + motd[2];
			}
			if (motd[0].equalsIgnoreCase("Finalizado")) {
				hg3 = "§6" + motd[1] + " Venceu!";
				hg3t = "§e--";
				hg3o = "§e--";
			}
		} else {
			hg3 = "§eOffline";
			hg3t = "§c--";
			hg3o = "§c--";
		}

Só que todos ficam voltando offline '-'

Motivo disso é que o sistema ta carregando na Thread e nao deu ainda, entao ela retorna OFF, vc vai ter que fazer a implementação na PLACA com Thread ouu

Voce pode construir uma List com os servidores e fazer update em cada servidor em cada tempo e pegar dessa lista para colocar na placa, assim nao vai dar problema de tar offfline somente quanto estiver mesmo

Link para o comentário
Compartilhar em outros sites

Motivo disso é que o sistema ta carregando na Thread e nao deu ainda, entao ela retorna OFF, vc vai ter que fazer a implementação na PLACA com Thread ouu

Voce pode construir uma List com os servidores e fazer update em cada servidor em cada tempo e pegar dessa lista para colocar na placa, assim nao vai dar problema de tar offfline somente quanto estiver mesmo

Tipo.... Não entendi muito bem...

 

Fazer uma Hasmap e ficar colocando o resultado do servidor?

 

(... Eu fiz 3 de esse código ex:

Status1 Status2 e Status3

No status1 mando um request ... No outro também... Isso não serve? (Não estou conseguindo pegar o resultado de cada request por que fica atualizando em forma geral ...)) (Atualmente todos online os dados ficam tipo os 3 iguais ... E mudando para os status dos 3 servidores rapidamente)

 

@Edit

Agora que entrei pelo pc notei que esse topico ja foi marcado como resolvido hehe ... achei que tinha respondido nesse outro: http://gamersboard.com.br/topic/40964-api-resultado-individual/

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

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