javapythonsockets

Unable to receive string data from Python socket to Java socket


I am having trouble with using sockets. As you can see, the code worked when I tried to send string from Java to Python.

However, I am having trouble when I tried to send string from Python to Java, which is the opposite way. I need it to convert into bytes and decode it since I encoded the string before I send it over.

The problem now is how or is there anything wrong in my codes when I send a string from Python socket and receiving the string by Java socket?

Python (server) code:

import socket
import ssl
import hashlib
import os
from Crypto.Cipher import AES
import hashlib
from Crypto import Random 

sHost = ''
sPort = 1234


def bindSocket():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #IPv4 and TCP
    try:
        s.bind((sHost,sPort))
        print("Socket created and binded")
    except socket.error as msgError:
        print(msgError)
        print("Error in Binding Socket")
    return s #so that we can use it


def socketConnect():
    s.listen(1) #listen to 1 connection at a time

    while True:
        try:
            conn, address = s.accept() #Accept connection from client
            print ("Connected to: " + address[0] + ":" +str(address[1]))
        except socket.error as error:
            print ("Error: {0}" .format(e))
            print ("Unable to start socket")
        return conn


def loopCommand(conn):
    while True:
        passphrase = "Hello Java Client "
        data = conn.recv(1024)#receive the message sent by client
        
        print(data)
        
        conn.send(passphrase.encode('utf-8'))
        
        print("Another String is sent to Java")


s = bindSocket()

while True:
    try:
        conn = socketConnect()
        loopCommand(conn)
    except:
        pass

Java (client) code:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketSTesting {

    public Socket socketStartConnect() throws UnknownHostException, IOException {
        String ip = "192.168.1.16";
        int port = 1234;
        Socket clientSocket = new Socket(ip, port);
        if (clientSocket.isConnected()) {
            System.out.println("It is connected to the server which is " + clientSocket.getInetAddress());

        } else if (clientSocket.isClosed()) {
            System.out.println("Connection Failed");
        }
        return clientSocket;
    }

    public void sendString(String str) throws Exception {
        // Get the socket's output stream
        Socket socket = socketStartConnect();
        OutputStream socketOutput = socket.getOutputStream();
        
        byte[] strBytes = str.getBytes();

        // total byte
        byte[] totalByteCombine = new byte[strBytes.length];
        System.arraycopy(strBytes, 0, totalByteCombine, 0, strBytes.length);

        //Send to Python Server
        socketOutput.write(totalByteCombine, 0, totalByteCombine.length);
        System.out.println("Content sent successfully");
        
        //Receive Python string
        InputStream socketInput = socket.getInputStream();
        String messagetype = socketOutput.toString();
        System.out.println(messagetype);

    }

    public static void main(String[] args) throws Exception {
        SocketSTesting client = new SocketSTesting();
        
        String str = "Hello Python Server!";
        client.sendString(str);
    }
}

Solution

  • You seem to think that String messagetype = socketOutput.toString(); performs I/O. It doesn't, so printing it or even calling it does nothing and proves nothing. You need to read from the socket input stream.

    BTW clientSocket.isConnected() cannot possibly be false at the point you are testing it. If the connect had failed, an exception would have been thrown. Similarly, clientSocket.isClosed() cannot possibly be true at the point you are testing it, because you haven't closed the socket you just created. Further, if isClosed() was true it would not mean 'connection failed', and isConnected() being false does not entail isClosed() being true. Remove all this.