在Java线程中的while循环不运行

huangapple go评论117阅读模式
英文:

While loop in java thread doesn't run

问题

以下是您要翻译的部分:

我正在制作一个Minecraft模组,在其中我想要在后台运行一个套接字服务器,等待来自Python客户端的消息。

服务器在一个线程中运行。

这是我启动线程的代码:
```java
Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    InterPythonJavaCommunicatorServer.begin(socket, sockIn, sockOut);
                }catch (IOException e){
                    System.out.println("哇!出了点问题!现在响起警报!");
                }
            }
        });
        t.start();
        t.join();

和整个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("测试!");
            boolean ready = sockIn.ready();
            if(!ready) {
                return;
            }
            try {
                String response = sockIn.readLine(); // 停在这里!
                System.out.println(response);
                //if (response == null) {
                    //System.out.println("远程进程关闭了连接。");
                    //done=true;
                //}
                if (response.equals("前进\n")){
                    boolean o = Movement.forward(1);
                    if (o){
                        sockOut.write("完成");
                        sockOut.flush();
                    }
                }
            } catch (IOException e) {
                System.out.println("哎呀!警报哥哥!");
            }
        }
    }
}

我已经设置断点,整个代码似乎停在String response = sockIn.readLine();上。而且测试!消息只运行一次。

Ps:我已经谷歌了几个小时搜索原因!似乎找不到相关的信息!

我知道这可能非常愚蠢,容易被发现 在Java线程中的while循环不运行

编辑:正如@DevParzival所说,我尝试使用t.join();但结果仍然相同!我已编辑上述代码以匹配我的当前代码。

编辑2:这是客户端代码(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)

提前谢谢!



<details>
<summary>英文:</summary>

I am making a Minecraft mod in which I want to have a socket server running in the background waiting for a message from the python client.

The server is running in a thread.

Here is the code in which I start the thread: 
```java
Thread t = new Thread(new Runnable() {

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


And the entire Server class


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(&quot;Test!&quot;);
            boolean ready = sockIn.ready();
            if(!ready) {
                return;
            }
            try {
                String response = sockIn.readLine(); // Stops Here!
                System.out.println(response);
                //if (response == null) {
                    //System.out.println(&quot;Remote process closed the connection.&quot;);
                    //done=true;
                //}
            if (response.equals(&quot;forward\n&quot;)){
                    boolean o = Movement.forward(1);
                    if (o){
                        sockOut.write(&quot;done&quot;);
                        sockOut.flush();
                    }
                }
            } catch (IOException e) {
                System.out.println(&quot;Welp! ALARM BOI!&quot;);
            }
        }
    }

}



I have breakpoined the entire code and it seems to stop on String response = sockIn.readLine();. And the Test! message only runs once.

Ps: I have googled for hours searching why! cant seem to find anything related!

I know it might be very stupid and easiely caught out 在Java线程中的while循环不运行

Edit: As @DevParzival Said I tried using t.join(); but it still does the same! I have edited the above code to match my current one.

Edit2: here is the client code(python)

import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((&quot;&quot;, 1243))
server_socket.listen(5)

print(
    &quot;TCPServer Waiting for client on port 1243&quot;)

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

        data = client_socket.recv(512)
        if data == &#39;q&#39; or data == &#39;Q&#39;:
            client_socket.close()
            break
        else:
            print(&quot;RECEIVED:&quot;, data)

Thx in advance

答案1

得分: 0

尝试在Python数据包的末尾发送NewLine | CHR(10) | \n字符,如果在接收端使用socketIn.readLine(),它会在返回之前等待行分隔符。

如果您想研究Java的非阻塞NIO套接字,可以在这里研究我的示例程序,请注意NIO套接字需要一种相当不同的方法。
链接:https://stackoverflow.com/a/26312841/185565

英文:

Try to send NewLine | CHR(10) | \n character at the end of python packet payload, if you use socketIn.readLine() in a receiving side it waits for a line delimiter before return.

If you want to study Java NonBlocking NIO socket you may study my example program here, please note NIO socket need quite a different approach
https://stackoverflow.com/a/26312841/185565

huangapple
  • 本文由 发表于 2020年10月27日 16:41:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/64550765.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定