I need to connect using Java and Python sockets. I wrote code to create a server in Python and code to create a client in Java to be able to communicate between Python and Java.
The connection is created correctly, when sending data from Java to Python using writeUTF() it works, but when sending from Python and reading with java using readUTF(), I get an EOF exception. The funny thing is that if I read from Java with the readLine() method, it works.
The server code:
import socket
ser = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ser.bind(("localhost", 7000))
ser.listen(1)
cli, addr = ser.accept()
recibido = cli.recv(1024)
recibido = recibido.decode("UTF8")
print("Recibo conexion de la IP: " + str(addr[0]) + " Puerto: " + str(addr[1]))
print(recibido)
enviar = "hola tio".encode("UTF8")
cli.send(enviar)
cli.close()
ser.close()
print("Conexiones cerradas")
The client code:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Cliente {
public static void main(String[] args) throws IOException, InterruptedException {
Socket cliente = new Socket("localhost", 7000);
DataOutputStream entrada = new DataOutputStream(cliente.getOutputStream());
DataInputStream salida = new DataInputStream(cliente.getInputStream());
entrada.writeUTF("Hola soy cliente");
System.out.println(salida.readUTF());
cliente.close();
}
}
The exception:
Exception in thread "main" java.io.EOFException
at java.base/java.io.DataInputStream.readFully(DataInputStream.java:202)
at java.base/java.io.DataInputStream.readUTF(DataInputStream.java:614)
at Cliente.main(Cliente.java:15)
writeUTF(), but it actually doesn't (or at least, you missed the fact that the string received by the server contains two additional characters: NUL (0x00) and LF (0x10).