putty174
putty174

Reputation: 315

Extra characters when sending String from Android client to Python Server

I am sending a String from an Android device to a python server via TCP socket, but when the message arrives on the server, there are extra characters in the front. For example, if I send the string

asdf

the result on the server would be

\x00\x13asdf

Anyone know why these characters are added to the front of the string? Is there a way to avoid this, or should I just cut these out at the server end?

For the reverse, the server sends

fdsa

The Android client receives

Nullfdsa

Client Code (Written in Android, Java):

public static class PlaceholderFragment extends Fragment {

        TextView recieve;
        EditText addressText, portText, messageText;
        Button send, test;

        Socket socket = null;

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(
                    R.layout.fragment_customize_gateway, container, false);

            recieve = (TextView) rootView.findViewById(R.id.textView1);
            addressText = (EditText) rootView.findViewById(R.id.editText1);
            portText = (EditText) rootView.findViewById(R.id.editText2);
            messageText = (EditText) rootView.findViewById(R.id.editText3);

            send = (Button) rootView.findViewById(R.id.send);
            send.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    AsyncTCPSend tcpSend= new AsyncTCPSend(addressText.getText().toString(),Integer.parseInt(portText.getText().toString()), messageText.getText().toString());
                    tcpSend.execute();
                }
            });
            return rootView;
        }

public class AsyncTCPSend extends AsyncTask<Void, Void, Void> {
            String address;
            int port;
            String message;
            String response;
            AsyncTCPSend(String addr, int p, String mes) {
                address = addr;
                port = p;
                message = mes;
            }

            @Override
            protected Void doInBackground(Void... params) {
                Socket socket = null;
                try {
                    socket = new Socket("127.0.0.1", 4999);
                    DataOutputStream writeOut = new DataOutputStream(socket.getOutputStream());
                    writeOut.writeUTF(message);
                    writeOut.flush();

                    ByteArrayOutputStream writeBuffer = new ByteArrayOutputStream(1024);
                    byte[] buffer = new byte[1024];

                    int bytesRead;
                    InputStream writeIn = socket.getInputStream();

                    while((bytesRead = writeIn.read(buffer)) != -1) {
                        writeBuffer.write(buffer,0,bytesRead);
                        response += writeBuffer.toString("UTF-8");
                    }
                    response = response.substring(4);   //Server sends extra "Null" string in front of data. This cuts it out
                } catch (UnknownHostException e){
                    e.printStackTrace();
                    response = "Unknown HostException: " + e.toString();
                    System.out.println(response);
                } catch (IOException e) {
                    response = "IOException: " + e.toString();
                    System.out.println(response);
                } finally {
                    if (socket != null) {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                recieve.setText(response);
                super.onPostExecute(result);
            }
        }

Server Code (In Python):

class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
    def handle(self):
        #Connect to database
        try:
            from pymongo import MongoClient
            dbclient = MongoClient()
            db = dbclient.WDI_database
            print("Database Connected")
        except pymongo.errors.ConnectionFailure as e:
            print("Database Failed: {}".format(e))

        col = db.users

        data2 = str(self.request.recv(1024), 'utf-8')
        print("Server: {}".format(data2));
        data = data2.split("||")
        try:
            #[2:] because we get two extra symbols in front of the username from Android
            username = data[0][2:] 
        except IndexError:
            username = ""
        try:
            password = data[1]
        except IndexError:
            password = ""
        try:
            camunits = data[2]
        except IndexError:
            camunits = 0
        try:
            homunits = data[3]
        except IndexError:
            homunits = 0
        post = {"user": username,
                "pass": password,
                "cam": camunits,
                "disp": homunits}
        col.insert(post)
        print(col.count())

        response = bytes("Received data for: {}".format(username), 'utf-8')
        self.request.sendall(response)

class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    pass

if __name__ == "__main__":
    # Port 0 means to select an arbitrary unused port
    HOST, PORT = "", 5000

    tcpserver = ThreadedTCPServer((HOST, PORT-1), ThreadedTCPRequestHandler)
    server_thread = threading.Thread(target=tcpserver.serve_forever)
    server_thread.daemon = True
    server_thread.start()
    print("TCP serving at port", PORT-1)

    while True:
        pass
    tcpserver.shutdown()

Upvotes: 0

Views: 1623

Answers (2)

Mithun Mistry
Mithun Mistry

Reputation: 148

Let java send the extra character. It did in my case too. I used -

data2 = data.strip()

if data2 == "(your desired data)"

//execution instructions

and so on.

Upvotes: 0

ja_mesa
ja_mesa

Reputation: 1969

I think I got some explanations about the extra characters.

In the java code, you are not getting an extra "Null" from the socket, the response string variable is not initialized, by default it is null, and you say

response += writeBuffer.toString("UTF-8");

so you append something to a null string, which happened to be "null" + something.

I would initialize the variable in the declaration or just before the while loop:

String response = "";

In the Phyton code, I see nothing wrong, therefore I'd suggest you to write what you send to the Log and see if the extra characters are in the bytes you send.

Instead of writeOut.writeUTF(message);

try socket.getOutputStream().write(message.getBytes()); // UTF-8 is the default.

and write it to the Log:

android.util.Log.w("SENT", String.format("[%s] %d", message, message.length()));

See the log to find out what you're really sending.

Upvotes: 1

Related Questions