1

I have a client program in java that sends a message "Hello" to python server.

Java code

    import java.io.*;  
    import java.net.*; 
    public class MyClient {
    public static void main(String[] args) {  

    try{      
    Socket soc=new Socket("localhost",2004);  
    DataOutputStream dout=new DataOutputStream(soc.getOutputStream());  
    dout.writeUTF("Hello");
    dout.flush();
    dout.close();  
    soc.close();
    }catch(Exception e){
        e.printStackTrace();}  
    }  

Python server code

    import socket               # Import socket module

    soc = socket.socket()         # Create a socket object
    host = "localhost" # Get local machine name
    port = 2004                # Reserve a port for your service.
    soc.bind((host, port))       # Bind to the port
    soc.listen(5)                 # Now wait for client connection.
    while True:
    conn, addr = soc.accept()     # Establish connection with client.
    print ("Got connection from",addr)
    msg = conn.recv(1024)
    print (msg)
    if ( msg == "Hello Server" ):
    print("Hii everyone")
    else:
    print("Go away")

the problem is that java client is able to send a Hello message to the python server but in python side else statement always executes with output " Go away".python version 2.7

Output:

('Got connection from', ('127.0.0.1', 25214))
Hello
Go away
Adi
  • 2,364
  • 1
  • 17
  • 23
user3832276
  • 11
  • 1
  • 1
  • 4
  • Python does not understand Java's `writeUTF()` format. Only Java's `writeUTF()` understands it. Use `writeBytes()`. – user207421 Mar 02 '19 at 08:38

5 Answers5

4

you are getting 'Hello' from client.

if ( msg == "Hello" ):
    print("Hii everyone")
else:
    print("Go away")
Adi
  • 2,364
  • 1
  • 17
  • 23
1

because the string you get on the server side has 2 hidden characters at the beginning, so you must remove these 2 characters before comparing it.

if ( msg[2:] == "Hello" ):
0

In the Java code you have written

dout.writeUTF("Hello");

But the Python server expects "Hello Server" to print "Hii Everyone".

Change Java Client code to

dout.writeUTF("Hello Server");
Erick
  • 49
  • 6
-1

Just Use proper syntax. Since you are sending "Hello", "Go away" will be your output.

if ( msg == "Hello Server" ):
    print("Hii everyone")
else:
    print("Go away")
-1

The problem is that you have to specify the decryption UTF-8 in the Python server and then you should use dout.writeBytes("Hello Server") in the Java client.

Employee
  • 3,109
  • 5
  • 31
  • 50