carlos palma
carlos palma

Reputation: 834

connecting python socket and java socket

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.

Upvotes: 5

Views: 15542

Answers (3)

Ganesh Jagdale
Ganesh Jagdale

Reputation: 51


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(); 
  }
  }
  }

Upvotes: 1

carlos palma
carlos palma

Reputation: 834

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

Upvotes: 9

akshit m
akshit m

Reputation: 728

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!

Upvotes: 0

Related Questions