0

I try to create a Socket messager between a Java Client and Python Server. It works to send a message ("Testdata") from client to server and print it out. But after input and send a message from server to client, I get no output from client. The client 'freezes' and must be terminated.

What is the problem with my client input?


Terminal Server:

py socketServer.py
Connection from: ('127.0.0.1', 57069)
from connected user: Testdata
> Test
send data..

Terminal Client:

java socketClient   
Testdata

Python-Server:

import socket

def socket_server():
    host = "127.0.0.1"
    port = 35100

    server_socket = socket.socket()
    server_socket.bind((host, port))
    server_socket.listen(2)
    conn, address = server_socket.accept()
    print("Connection from: " + str(address))
    while True:
        data = conn.recv(1024).decode()
        if not data:
            break
        print("from connected user: " + str(data))
        data = input('> ')
        conn.send(data.encode())
        print("send data...")
    conn.close()

if __name__ == '__main__':
    socket_server()

Java-Client:

private static void socketTest(){
    String hostname = "127.0.0.1";
    int port = 35100;

    try (Socket socket = new Socket(hostname, port)) {
        OutputStream output = socket.getOutputStream();
        PrintWriter writer = new PrintWriter(output, false);

        BufferedReader input =
                new BufferedReader(
                        new InputStreamReader(socket.getInputStream()));
        Scanner in = new Scanner(System.in);
        String text;

        do {
            text = in.nextLine();
            writer.print(text);
            writer.flush();
            System.out.println("from server: " + input.readLine());
        } while (!text.equals("exit"));

        writer.close();
        input.close();
        socket.close();
    }
}
2
  • You can look over this answer. ( @carlos palma ) Commented Jan 20, 2020 at 8:38
  • Your client is reading lines but your server isn't sending lines. Commented Jan 20, 2020 at 11:32

1 Answer 1

0

This is because python messages are not explicitly finished with \r\n like @carlos palmas says in this answer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.