5

I have been trying to send a simple string between a Java client socket and a Python server socket. This is the code for the server socket:

HOST=''
PORT=12000
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADRR,1)
s.bind((HOST,PORT))
s.listen(5)
device=variador()
while True:

  conn,addr=s.accept()
  if data=="turn_on":
     respuesta=device.send_order(variador.start_order)
     conn.send(respuesta+'\n')
     conn.close()

and the client code is:

   try {

            Socket socket = new Socket("192.168.10.171", 12000);

            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

            BufferedReader in = new BufferedReader(new InputStreamReader(
                                       socket.getInputStream()));    

            BufferedReader stdIn = new BufferedReader(
                                          new InputStreamReader(System.in));

            out.print(command);

            out.close();
            in.close();
            socket.close();

        } catch (UnknownHostException e) {
            System.err.println("Unknown Host.");
           // System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for "
                               + "the connection.");
          //  System.exit(1);
        }

Everything works fine until I try to read the server's response, using this:

    String userInput;
  while ((userInput = stdIn.readLine()) != null) {
  out.println(userInput);
  System.out.println("echo: " + in.readLine());
  }

then the code hangs and the Python server does not receive any information, which I tested using print.

Is there a problem trying to send first and then wait for a response from the server in the Java client?

Any help will be much appreciated.

rgettman
  • 176,041
  • 30
  • 275
  • 357
carlos palma
  • 722
  • 3
  • 12
  • 29
  • You don't receive anything in the server? Instead you seem to only accept the connection, and if a condition is true you write some data and directly closes the connection. If the condition is not true then you don't seem to close the socket at all, but neither do you receive anything. – Some programmer dude Jan 03 '14 at 22:05
  • When the java client sends "turn_on" I can print that on the console in python, therefore it arrives. – carlos palma Jan 04 '14 at 12:59

3 Answers3

9

Well, I discovered that the Java client hangs because the messages sent by the python server were not explicitly finished with \r\n, so the Python code should have been something like this:

HOST = ''
PORT = 12000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADRR, 1)
s.bind((HOST, PORT))
s.listen(5)
device = variador()
while True:

    conn, addr = s.accept()
    if data == "turn_on\r\n":
        respuesta = device.send_order(variador.start_order)
        conn.send(respuesta + '\r\n')
    conn.close()

I know it should have been quite obvious from the name of the methods in Java, readline() and println, both suggesting that java ends strings with the sequence \r\n

Boern
  • 7,233
  • 5
  • 55
  • 86
carlos palma
  • 722
  • 3
  • 12
  • 29
1

Connect Python And Java Sockets


Install the package jpysocket

pip install jpysocket

https://pypi.org/project/jpysocket

Import Library jpysocket

The Followings Are The Some Example

Python Server :

import jpysocket
import socket

host='localhost' #Host Name
port=12345    #Port Number
s=socket.socket() #Create Socket
s.bind((host,port)) #Bind Port And Host
s.listen(5) #Socket is Listening
print("Socket Is Listening....")
connection,address=s.accept() #Accept the Connection
print("Connected To ",address)
msgsend=jpysocket.jpyencode("Thank You For Connecting.") #Encript The Msg
connection.send(msgsend) #Send Msg
msgrecv=connection.recv(1024) #Recieve msg
msgrecv=jpysocket.jpydecode(msgrecv) #Decript msg
print("From Client: ",msgrecv)
s.close() #Close connection
print("Connection Closed.")

Java Client :

import java.io.*;  
  import java.net.*; 
  public class Client {
  public static void main(String[] args) {  
  try{      
  Socket soc=new Socket("localhost",12345);  
  DataOutputStream dout=new DataOutputStream(soc.getOutputStream());  
  DataInputStream in = new DataInputStream(soc.getInputStream());
  String msg=(String)in.readUTF();
  System.out.println("Server: "+msg);
  dout.writeUTF("Ok Boss");
  dout.flush();
  dout.close();
  soc.close();
  }
  catch(Exception e)
  {
      e.printStackTrace(); 
  }}}  

Python Client :

import jpysocket
import socket

host='localhost' #Host Name
port=12345    #Port Number
s=socket.socket() #Create Socket
s.connect((host,port)) #Connect to socket
print("Socket Is Connected....")
msgrecv=s.recv(1024) #Recieve msg
msgrecv=jpysocket.jpydecode(msgrecv) #Decript msg
print("From Server: ",msgrecv)
msgsend=jpysocket.jpyencode("Ok Boss.") #Encript The Msg
s.send(msgsend) #Send Msg
s.close() #Close connection
print("Connection Closed.")

Java Server :

import java.io.*;  
import java.net.*; 
public class Server {
  public static void main(String[] args) {
      try{ 
      ServerSocket serverSocket = new ServerSocket(12345);
      Socket soc = serverSocket.accept();
      System.out.println("Receive new connection: " + soc.getInetAddress());
      DataOutputStream dout=new DataOutputStream(soc.getOutputStream());  
      DataInputStream in = new DataInputStream(soc.getInputStream());
      dout.writeUTF("Thank You For Connecting.");
      String msg=(String)in.readUTF();
      System.out.println("Client: "+msg);
      dout.flush();
      dout.close();
      soc.close();
      }
      catch(Exception e)
      {
      e.printStackTrace(); 
  }
  }
  }
0

If you only want to send a single command on the socket connection, then close the OutputStream after writing the command (using Socket.shutdownOutput()). The socket is reading until EOF and you will not receive EOF until you close the socket. hence, your code never proceeds.

Source - java socket InputStream hangs/blocks on both client and server

Hope it helps!

Community
  • 1
  • 1
akshitmahajan
  • 668
  • 1
  • 9
  • 17