0

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);
 }
}
Mark Rotteveel
110k241 gold badges160 silver badges233 bronze badges
asked Jul 29, 2018 at 3:26
2
  • 5
    I don't know if this is your problem, but it's certainly a problem. TCP is not a stream of messages, it's just a stream of bytes. So how is Java supposed to know when you've sent your whole string? It's like expecting Java to knowwhereawordendswhenyoudon'tputanyspaces. You need some kind of framing, like maybe a newline at the end of the string, so it knows to read until a newline. Commented Jul 29, 2018 at 3:47
  • 4
    But meanwhile, you don't seem to be even trying to read anything from the inputstream. Instead, you're just converting the output stream to a string and printing that. That's why you're not seeing any data from Python. Commented Jul 29, 2018 at 3:49

1 Answer 1

0

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.

answered Jul 29, 2018 at 4:31
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.