如何为Swing GUI创建套接字管理器?

时间:2014-07-09 02:37:06

标签: java swing sockets try-with-resources utility-method

现在我有一个控制台客户端,它通过ObjectInputStream.readObject()ObjectOutputStream.writeObject()与服务器通信。对于基于控制台的应用程序,这似乎可以正常工作。

问题是具有i / o流的类还引用了System.console()对象!

如何重构这个类以使它更通用?我几乎想要将连接视为一个实用程序,或者可能作为一个bean,然后将其传递给,例如,Swing GUI,或者可能是系统控制台。 / p>

package net.bounceme.dur.client;

import net.bounceme.dur.data.Title;
import java.net.*;
import java.io.*;
import java.util.Arrays;
import java.util.logging.Logger;
import net.bounceme.dur.data.State;

public class Client {

    private static final Logger log = Logger.getLogger(Client.class.getName());
    private String server = "localhost";
    private int portNumber = 8080;
    private final Console c = System.console();

    private Client() {
    }

    public Client(String server, int portNumber) {
        this.server = server;
        this.portNumber = portNumber;
    }

    public void inputOutput() throws IOException, ClassNotFoundException {
        Socket socket = new Socket(server, portNumber);
        boolean eof = false;
        Title title = null;
        State state = State.undefined;
        try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream())) {
            do {
                try {
                    title = (Title) objectInputStream.readObject();
                    log.info(title.toString());
                    do {
                        state = State.undefined;
                        try {
                            c.printf("enter the state for record:");
                            state = State.valueOf(c.readLine());
                        } catch (java.lang.IllegalArgumentException iae) {
                            log.warning(Arrays.deepToString(State.values()));
                        }
                    } while (state == State.undefined);
                    title.setState(state);
                    title.setTitle("modified from client");
                    objectOutputStream.writeObject(title);
                } catch (java.io.EOFException eofe) {
                    eof = true;
                }
            } while (!eof);
        }
    }

}

另见:

Java - Sockets and Swing

0 个答案:

没有答案