简体   繁体   English

通过套接字连接发送String []数组

[英]Send a String[] array over Socket connection

So I'm trying to send a String[] over an open socket connection. 因此,我试图通过开放的套接字连接发送String[] 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: 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. 在另一端收到String[] ,我希望能够像通常那样遍历它,以便获取值。 My current code doesn't seem to works as it returns null as the value. 我当前的代码似乎不起作用,因为它返回null作为值。

Is this possible? 这可能吗?

My current code doesn't seem to works as it returns null as the value. 我当前的代码似乎不起作用,因为它返回null作为值。

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"! 这就是说“如果出现问题,请返回null ,不要告诉我问题出在哪里”!

Catching and squashing exceptions like that is BAD PRACTICE. 捕获和压榨异常是不良实践。 At the very least, you should try to print an exception stacktrace. 至少,您应该尝试打印异常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: 您确实应该打印完整的stacktrace,如下所示:

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! 谢谢大家!

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

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