简体   繁体   中英

How to Send 2 different type of data in 1 socket in java

can somebody help me to send 2 different data type over 1 socket only from android to java server ... i have to send an array and a string together. Its crashing the app

   private void Send()
{
    Thread t = new Thread() {

        public void run() {

            try {

                Socket s = new Socket("192.168.0.3", 7000);
                ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());

                out.writeObject(array);
                out.flush();
                out.close();

                DataOutput out1 =new DataOutput(s.getOutputStream()); 
                out1.writeUTF(id); 
                out1.flush(); 
                out1.close;
                s.close();

            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    t.start();

    Toast.makeText(MainActivity.this, "Message Sent !", Toast.LENGTH_SHORT).show();
}

I am assuming that the error in your code is, that the Outputstream of your Socket is allready closed. The problem is that, if you close anykind of stream, all underlying streams are also closed. So if you close your ObjectOutputStream, the stream from the socket is closed automatically too.

If I were you, I would create a new class holding all the data you need, and send only an instance of this class.

    class TempObject {

        public TempObject(Object[] array, String id) {
            this.array = array;
            this.id = id;
        }

        public Object[] array;
        public String id;
    }

    private void Send() {

        TempObject obj = new TempObject(array, id);
        Socket s = new Socket("192.168.0.3", 7000);
        ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
        out.writeObject(obj);
        out.flush();
        out.close();
    }

If you want to send more then one element use table or collection. If you want to send string and int variable, you can create your own class to store them.

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