Mientras que el bucle en el hilo de java no se ejecuta

Oct 27 2020

Estoy haciendo un mod de Minecraft en el que quiero tener un servidor de socket ejecutándose en segundo plano esperando un mensaje del cliente de Python.

El servidor se está ejecutando en un hilo.

Aquí está el código en el que comienzo el hilo:

Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    InterPythonJavaCommunicatorServer.begin(socket, sockIn, sockOut);
                }catch (IOException e){
                    System.out.println("Woah! Somethings gone wrong! ringing a alarm now!");
                }
            }
        });
        t.start();
        t.join();


Y toda la clase Server


package com.satyamedh.minecraft_ai_helper.communicator;

import com.satyamedh.minecraft_ai_helper.Movement;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.net.Socket;

public class InterPythonJavaCommunicatorServer{

    public static void begin(Socket socket, BufferedReader sockIn, BufferedWriter sockOut) throws IOException {
        boolean done = false;
        while (true) {
            System.out.println("Test!");
            boolean ready = sockIn.ready();
            if(!ready) {
                return;
            }
            try {
                String response = sockIn.readLine(); // Stops Here!
                System.out.println(response);
                //if (response == null) {
                    //System.out.println("Remote process closed the connection.");
                    //done=true;
                //}
            if (response.equals("forward\n")){
                    boolean o = Movement.forward(1);
                    if (o){
                        sockOut.write("done");
                        sockOut.flush();
                    }
                }
            } catch (IOException e) {
                System.out.println("Welp! ALARM BOI!");
            }
        }
    }

}



He roto todo el código y parece detenerse String response = sockIn.readLine();. Y el Test!mensaje solo se ejecuta una vez.

Ps: ¡He buscado en Google durante horas buscando por qué! parece que no puedo encontrar nada relacionado!

Sé que podría ser muy estúpido y fácilmente atrapado :)

Editar: Como dijo @DevParzival, intenté usarlo, ¡ t.join();pero todavía hace lo mismo! He editado el código anterior para que coincida con el actual.

Edit2: aquí está el código del cliente (python)

import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("", 1243))
server_socket.listen(5)

print(
    "TCPServer Waiting for client on port 1243")

while 1:
    client_socket, address = server_socket.accept()
    print(
        "I got a connection from ", address)
    while 1:
        data = input("SEND( TYPE q or Q to Quit):")
        if data == 'Q' or data == 'q':
            client_socket.send(bytes(data, encoding='utf8'))
            client_socket.close()
            break
        else:
            client_socket.send(bytes(data, encoding='utf8'))

        data = client_socket.recv(512)
        if data == 'q' or data == 'Q':
            client_socket.close()
            break
        else:
            print("RECEIVED:", data)

Gracias de antemano

Respuestas

Whome Oct 27 2020 at 16:29

Intente enviar un NewLine | CHR(10) | \ncarácter al final de la carga útil del paquete de Python, si lo usa socketIn.readLine()en un lado de recepción, espera un delimitador de línea antes de regresar.

Si desea estudiar el socket NIO de Java NonBlocking, puede estudiar mi programa de ejemplo aquí, tenga en cuenta que el socket NIO necesita un enfoque bastante diferente https://stackoverflow.com/a/26312841/185565