Socket Java client - Python Server

后端 未结 1 972
囚心锁ツ
囚心锁ツ 2020-12-30 14:19

I\'m tring to implement a java - python client/server socket. The client is in java and the server is write in python

Java Client

im         


        
相关标签:
1条回答
  • 2020-12-30 15:15

    It seems that your indentation is off in the Python server, as the code to send the message back to the client is unreachable.

    Even after fixing the indentation, your server implementation is not correct, as msg is not a String. You need to decode msg as seen below. Also, you need to send the length of the message as a short since you're using DataInputStream#readUTF in your client:

    import socket
    
    soc = socket.socket()
    host = "localhost"
    port = 2004
    soc.bind((host, port))
    soc.listen(5)
    
    while True:
        conn, addr = soc.accept()
        print("Got connection from",addr)
        length_of_message = int.from_bytes(conn.recv(2), byteorder='big')
        msg = conn.recv(length_of_message).decode("UTF-8")
        print(msg)
        print(length_of_message)
    
        # Note the corrected indentation below
        if "Hello"in msg:
            message_to_send = "bye".encode("UTF-8")
            conn.send(len(message_to_send).to_bytes(2, byteorder='big'))
            conn.send(message_to_send)
        else:
            print("no message")
    
    0 讨论(0)
提交回复
热议问题