user1265125
user1265125

Reputation: 2656

Operating with Sockets between Python server and Android client

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?

Upvotes: 1

Views: 1608

Answers (1)

user2511414
user2511414

Reputation:

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
}

Upvotes: 1

Related Questions