简体   繁体   English

如何在Java中的1个套接字中发送2种不同类型的数据

[英]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. 有人可以帮我从Android到Java服务器仅通过1个套接字发送2种不同的数据类型吗?我必须一起发送数组和字符串。 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. 我假设您代码中的错误是,套接字的Outputstream已全部关闭。 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. 因此,如果关闭ObjectOutputStream,套接字的流也将自动关闭。

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. 如果要发送字符串和int变量,则可以创建自己的类来存储它们。

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

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