简体   繁体   English

将ObjectOutputStream传递给另一个类

[英]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 . 我正在开发一个GUI程序以在客户端/服务器系统中使用,它将数据保存在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. 建立连接时会创建一个ObjectOutputStreamObjectInputStream ,但是当我尝试打开一个连接时,我不确定如何将其传递到新类中。 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 在我的Startup类中,我有一个Serializable对象( Message m ),该对象已创建并传递到不同的类中,以修改不同的字段,以及在客户端和服务器之间建立连接

In my Startup class I have this code... 在我的Startup类中,我有以下代码...

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... WhatToDo类中,我有此代码...

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. 如果我像在Startup一样执行新的ObjectOutputStreamObjectInputStream ,则将创建到服务器的新连接。 I wish to use the existing Streams created in Startup in WhatToDo . 我希望使用WhatToDoStartup中创建的现有Streams 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 . 我使用的是带有按钮的ActionListener ,因此需要将流保存在构造函数中,以便以后在ActionListener使用。

I wish to use the existing Streams 我希望使用现有的流

That is exactly what your code does now. 这正是您的代码现在所做的。 Your comments about 'but need to construct' are incorrect. 您对“但需要构建”的评论不正确。

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

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