简体   繁体   中英

Android client with remote server

Im making an app that has to send a class to a server written in c++ using Sockets. The class consists of to variables both are Ints. I want to convert the java class into bytes then send it over the socket as a packet. The server is expecting 8 bytes for the packet size. When I try to convert my object I get more than 8 bytes. How else can I send my object to the server? Also the my code below sends 4 bytes of data in two 2 bytes chucks. Why is it doing that?

   public void connect2() {
        String serverHostname = new String("My IP");
        ObjectOutputStream out2 = null;
        ObjectInputStream in2 = null;

        try {

            echoSocket = new Socket(serverHostname, MYPORT);
            StatusPacket p = new StatusPacket();

        byte[] data = new byte[8];
        data  = serializeObject(p);
        int j = data.length;

            out2 = new ObjectOutputStream(echoSocket.getOutputStream());
            out2.flush();
            in2 = new ObjectInputStream(echoSocket.getInputStream());
            DataOutputStream dOut = new       DataOutputStream(echoSocket.getOutputStream());


               out2.write(data);

            out2.close();
            in2.close();
            echoSocket.close();


        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: " + serverHostname);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for "
                    + "the connection to: " + serverHostname);
            System.exit(1);
        }


    }

ObjectOutputStream and ObjectInputStream use Java serialization mechanisms, which includes a lot more info than just the class property values. You don't want to deal with those in C++ code, so I recommend you remove all serialization code and those two streams from your code.

Since you already know what you want on byte level, you should really be using that DataOutputStream instead. It allows you to transfer scalar data types like byte, int, long etc. without any overhead. Just get those two 32-bit integers from your object and pass them to DataOutputStream.writeInt(..) and you're set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM