1

I`m trying a socket connection between Java and Python. Are a dataOutput.writeUTF equivalent in Python to send and receive data?

Here`s an example of my code.

received = client.recv(1024)
print(received)
toSend = input()
client.send(toSend)
GBouffard
  • 1,125
  • 4
  • 11
  • 24

1 Answers1

0

As I had the same problem, here is a code sample that solves it:

#!/usr/bin/env python3

import socket
import struct

HOST = '127.0.0.1'  # The server's hostname or IP address
PORT = 6666        # The port used by the server

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))

    # Send message as UTF-8
    message = u"Hello from Python"
    data = bytearray(message, "utf8")
    size = len(data)
    s.sendall(struct.pack("!H", size))
    s.sendall(data)

    # Receive message
    data = s.recv(2)
    length = struct.unpack("!H", data)
    print("Length: {}".format(length))
    data = s.recv(1024)
    message = data.decode("utf-8")
    print("Received message: {}".format(message))

    s.close()

I found useful information here:

lauhub
  • 894
  • 1
  • 15
  • 27