How to send a string via a socket in python to a java server?

advertisements

I have the following problem: I made a simple java server and a python client, but, since I am new to python I don't know how to send a string over the socket, so that the java server can read it the right way. This is some of the code of the client (written in Python 3.5). The part with sock.send(b"1-4\n") successfully did the job and I got from the server the expected message.

...................
sock.connect((HOST, PORT))
sock.send(b"1-4\n")
data = sock.recv(102451223).decode()
print(data)
....................

But let's say that I want to get the input from the user and they only write "1-4". How to send the string input (I have input=("enter range:")) ? I tried with

sock.send(b""+input+"\n")

and it didn't work.

Thank you!


The problem is the way you encode your string:

socket.send(("string1" + "string2").encode())

This should do the thing.

Explanation:

Your code only encodes the first part of the string, but you have to encode the complete text that should be sent to the server.