Socket Java client - Python Server
Asked Answered
I

1

6

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

import java.io.*;  
import java.net.*; 
import java.lang.*;

public class client {

public static void main(String[] args) {  



    try{      
        Socket socket=new Socket("localhost",2004);  

        DataOutputStream dout=new DataOutputStream(socket.getOutputStream());  
        DataInputStream din=new DataInputStream(socket.getInputStream());


        dout.writeUTF("Hello");
        dout.flush();

        System.out.println("send first mess");
        String str = din.readUTF();//in.readLine();

        System.out.println("Message"+str);


        dout.close();  
        din.close();
        socket.close();
        }

    catch(Exception e){
        e.printStackTrace();}   


}  

}

Python server

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)
    msg = conn.recv(1024)
    print (msg)
    print(len(msg))

    if "Hello"in msg:
         conn.send("bye".encode('UTF-8'))
    else:
         print("no message")

The first message from client to server was delivery correctly but the second from server to client no. Using telnet I check that sever send the message but the client goes in deadlock and don't receive message. I don't understand why.

Thanks

Impenitent answered 15/1, 2018 at 15:31 Comment(0)
S
6

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")
Submultiple answered 15/1, 2018 at 16:8 Comment(1)
Thanks, your solution solve my problem, the wrong indentation is copy-paste mistake!Impenitent

© 2022 - 2024 — McMap. All rights reserved.