Search code examples
javaparameter-passingobjectoutputstreamobjectinputstream

Passing an ObjectOutputStream to another class


I am developing a GUI program to use in a client/server system that will save data in a Vector. I have an ObjectOutputStream and ObjectInputStream that is created when I make the connection, however I am not sure how to pass it into the new class when i try to open one up. In my Startup class I have a Serializable object (Message m) that is created and passed into different classes to have different fields modified, as well as the connection gets established between the client and server

In my Startup class I have this code...

m.yourName = tmyName.getText();
m.department = tdepartment.getText();

if (m.yourName != null && m.department != null) {
    client = new Socket(server, port);
    oout = new ObjectOutputStream(client.getOutputStream());
    oin = new ObjectInputStream(client.getInputStream());
    toutput.setText("Connected");
    oout.writeObject(m);
    new WhatToDo (m, oout, oin);
}

In the WhatToDo class i have this code...

Message m;
ObjectOutputStream oout;
ObjectInputStream oin;

public WhatToDo(Message a, ObjectOutputStream oout2, ObjectInputStream oin2){
    m = new Message();
    m = a;

    // this is what i'm unsure about and need help with
    oout = oout2; //but need to construct oout first
    oin = oin2; //but need to construct oin first
}

If i do the new ObjectOutputStream and ObjectInputStream like I did in Startup, i will create a new connection to the server. I wish to use the existing Streams created in Startup in WhatToDo. Thank you for your help in advance!

I'm using an ActionListener with button presses, so the streams will need to be saved in the constructor for later use in the ActionListener.


Solution

  • I wish to use the existing Streams

    That is exactly what your code does now. Your comments about 'but need to construct' are incorrect.