简体   繁体   中英

Java Socket Server Communication to Python client, program won't enter “inputLine = in.readLine()”-loop

I'm trying to create a socket server in Java that can communicate with a python client. I ran into the problem that everything executes fine if I start the server, send a message through python, and then immediately exit, but if the client sends a message and then listens to the socket again the server won't respond.

Here's the code, mostly taken from this example from oracle

public class PrimeServer {

    public static void main(String[] args) throws IOException {

        int portNumber = 4444;

        try (
                ServerSocket serverSocket = new ServerSocket(portNumber);
                Socket clientSocket = serverSocket.accept();
                PrintWriter out =
                        new PrintWriter(clientSocket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(clientSocket.getInputStream()))
        ) {

            String inputLine;
            String outputLine;
            String rawMessage;

            // Initiate conversation with client
            PrimeProtocol ppc = new PrimeProtocol();
            outputLine = String.format("%1022s", "Ready").replace(' ', '0');
            out.println(outputLine);
            System.out.println("Over while");
            while ((inputLine = in.readLine()) != null) {
                System.out.println("In while");
                if (ppc.processInput(Integer.parseInt(inputLine))){
                    rawMessage = "True";
                } else {
                    rawMessage = "False";
                }
                outputLine = String.format("%1024s", rawMessage).replace(' ', '0');
                System.out.println("Outputting " + rawMessage);
                out.println(outputLine);

            }
            System.out.println("Passed while.");
        } catch (IOException e) {
            System.out.println("Exception caught when trying to listen on port "
                    + portNumber + " or listening for a connection");
            System.out.println(e.getMessage());
        }
    }
}

And the python code for good measure:

msg_len = 1024
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1", 4444))
init_message = sock.recv(msg_len).decode("UTF-8")
init_message = init_message.replace('0', '')
print(init_message)
print(len(init_message))
sock.send(b'3')

With this code the output from the java server is:

Over while
In while
Outputting True
Passed while.

And the client output is:

1024
Ready

After which the connection breaks.

But if I add this line to the client: new_message = sock.recv(msg_len).decode("UTF-8") Making the new python:

msg_len = 1024
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1", 4444))
init_message = sock.recv(msg_len).decode("UTF-8")
print(len(init_message))
init_message = init_message.replace('0', '')
print(init_message)

sock.send(b'3')

new_message = sock.recv(msg_len).decode("UTF-8")

The server jams and the output is only:

Over while

While the client outputs:

1024
Ready

While also jamming.

Any ideas what is going on here?

Turns out it was the python socket that needed to flush. New python code:

msg_len = 1024
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1", 4444))
init_message = sock.recv(msg_len).decode("UTF-8")
print(len(init_message))
init_message = init_message.replace('0', '')
print(init_message)

sock.send(b'3\n')

new_message = sock.recv(msg_len).decode("UTF-8")
print(new_message)

(added \\n) to the message going out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM