1

I'm trying to send complex variable amounts of data from my Python server to my Android client over a TCP socket.

Since I'm sending variable amounts of data, I'll have to prefix my data with the length of the message, and then on the Android side I'll have to read that prefix first, and then read those number of bytes as a stream.
Am I right?

So here's how I'm doing it on the Server(Python) side:

def send_msg(sock, msg):
    msg = struct.pack('>I', len(msg)) + msg
    sock.sendall(msg)

But my Java is pretty weak and I can't figure how to receive this on the client side.

Any help?

1 Answer 1

1

not so hard dude, first you have to send the size of the data you want to send as integer/long value, no String. second, in the client side just after connecting to the server, get(read) one int/long value that indicates the amount of data should be sent, then wait for x bytes. while I suggest you just send the message as string with a \r then in the client side read a line which reads data till reaches \r, so in this way you would omit the size of the data at the first.

in java you may need these guys.

void Connect throws Exception{
DataInputStream dis;
DataOutputStream dos;
Socket s=new Socket("176.12.0.36",8903);//to connect address,port
dis=new DataInputStream(s.getInputStream());
dos=new DataOutputStream(s.getOutputStream());
//sending anything to the server with dos
int _sizeOfMessage=dis.readInt();//sends int value from server, no string
byte[] _data=new byte[_sizeOfMessage];
dis.read(_data);//filling the buffer
//do some business with _data
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.