简体   繁体   English

带有远程服务器的Android客户端

[英]Android client with remote server

Im making an app that has to send a class to a server written in c++ using Sockets. 我正在制作一个必须使用套接字将类发送到用c ++编写的服务器的应用程序。 The class consists of to variables both are Ints. 该类由to变量组成,均为Ints。 I want to convert the java class into bytes then send it over the socket as a packet. 我想将Java类转换为字节,然后将其作为数据包通过套接字发送。 The server is expecting 8 bytes for the packet size. 服务器期望数据包大小为8个字节。 When I try to convert my object I get more than 8 bytes. 当我尝试转换对象时,会得到8个以上的字节。 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. 同样,下面的我的代码以两个2字节的卡盘形式发送4字节的数据。 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. ObjectOutputStream和ObjectInputStream使用Java序列化机制,该机制不仅包含类属性值,还包含许多信息。 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. 您不想处理C ++代码中的代码,因此建议您从代码中删除所有序列化代码和这两个流。

Since you already know what you want on byte level, you should really be using that DataOutputStream instead. 由于您已经知道字节级别的要求,因此实际上应该使用该DataOutputStream。 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. 只需从您的对象中获得这两个32位整数,然后将它们传递给DataOutputStream.writeInt(..)就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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