简体   繁体   中英

Send a String[] array over Socket connection

So I'm trying to send a String[] over an open socket connection. I currently have this code:

Sending:

public void sendData() {
    try {
        OutputStream socketStream = socket.getOutputStream();
        ObjectOutputStream objectOutput = new ObjectOutputStream(socketStream);
        objectOutput.writeObject(new String[] {"Test", "Test2", "Test3"});

        objectOutput.close();
        socketStream.close();

    } catch (Exception e) {
        System.out.println(e.toString());
    }
}

Recieving:

public Object readData() {
    try {
    InputStream socketStream = socket.getInputStream();
    ObjectInputStream objectInput = new ObjectInputStream(new GZIPInputStream(socketStream));
    Object a = objectInput.readObject();
      return a;
    } catch(Exception e) {
        return null;
    }
}

After I have recieved the String[] on the other end I want to be able to iterate through it like I would do normally so I can get the values. My current code doesn't seem to works as it returns null as the value.

Is this possible?

My current code doesn't seem to works as it returns null as the value.

And it is pretty obvious why too!

} catch(Exception e) {
    return null;
}

That says "if something goes wrong, return null and don't tell me what the problem was"!

Catching and squashing exceptions like that is BAD PRACTICE. At the very least, you should try to print an exception stacktrace. In the writer code, you do this:

System.out.println(e.toString());

That is better than nothing, but it just prints the exception name and message. You should really be printing the full stacktrace ... like this:

e.printStackTrace(System.out);

And for production quality code, you should probably be LOGGING the exception, not just writing a message to standard output.

Once you have the stack trace, you can figure out what the real problem is and fix it.

I managed to figure it out on my own, I changed my recieving code to this:

public String[][] readData() {
    try {
    InputStream is = socket.getInputStream();
    ObjectInputStream ois = new ObjectInputStream(is);
     return (String[][])ois.readObject();
    } catch(Exception e) {
        return null;
    }
}

Works like a charm now. Thanks all!

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