0

不久前,我创建了一个程序,该程序创建套接字连接并将其输入集中到与我们的旧服务器的单个 telnet 连接。该项目的目标是为遗留数据库创建前端并最终迁移到现代数据库。我以一种我认为可以扩展到多个 telnet 连接的方式设置它。好吧,现在是我开始使用 2-4 连接到旧版服务器的时候了,但它不起作用。它总是将输入发送到最后建立的连接。这是我所做的:

1 类 - 服务器控制台

package serverconsole;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

/**
 *
 * @author Andrew
 */
public class ServerConsole {

    public static ArrayList<Boolean> busy = new ArrayList();
    public static ArrayList<MvTelnet> telnet = new ArrayList();
    static final Logger log = Logger.getLogger("errors");
    static FileHandler fh;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(5500)) {
            Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                @Override
                public void run() {
                    if (serverSocket != null) {
                        try {
                            serverSocket.close();
                        } catch (IOException ex) {
                            Logger.getLogger(ServerConsole.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }, "Shutdown-thread"));

            fh = new FileHandler("/mnt/javaprograms/ServerConsole/errors.log");
            log.addHandler(fh);
            SimpleFormatter formatter = new SimpleFormatter();
            fh.setFormatter(formatter);

            for(int i=0; i<2; i++) {
                busy.add(false);
                telnet.add(null);
            }

            while (true) {
                new MultiServerThread(serverSocket.accept()).start();
            }
        } catch (IOException e) {
            System.err.println(e);
            System.exit(-1);
        }
    }

    public static void log(String str) {
        log.info(str);
    }
}

2 类 - 多服务器线程

package serverconsole;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 *
 * @author Andrew
 */
public class MultiServerThread extends Thread {

    private Socket socket = null;

    public MultiServerThread(Socket socket) throws IOException {
        super("MultiServerThread");
        this.socket = socket;
    }

    @Override
    public void run() {
        try (
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))
            ;) {
            String input, output;
            while (true) {
                input = in.readLine();
                if (input.equals("Close")) {
                    break;
                }
                boolean written = false;
                while(written == false) {
                    for (int i=0;i < ServerConsole.busy.size(); i++) {
                        if (ServerConsole.busy.get(i) == false) {
                            ServerConsole.busy.set(i, true);
                            if (ServerConsole.telnet.get(i) == null) {
                                ServerConsole.telnet.set(i, new MvTelnet());
                            }
                            String response = ServerConsole.telnet.get(i).write(input);
                            out.println(response);
                            written = true;
                            ServerConsole.busy.set(i, false);
                            break;
                        }
                    }
                }
            }
            socket.close();
        } catch (IOException e) {
            ServerConsole.log(e.getMessage());
        }
    }
}

第 3 类 - MvTelnet 包 serverconsole;

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.apache.commons.net.telnet.EchoOptionHandler;
import org.apache.commons.net.telnet.InvalidTelnetOptionException;
import org.apache.commons.net.telnet.SuppressGAOptionHandler;
import org.apache.commons.net.telnet.TelnetClient;
import org.apache.commons.net.telnet.TerminalTypeOptionHandler;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

/**
 *
 * @author Andrew
 */
public class MvTelnet {
    static TelnetClient tc = null;
    private static DataInputStream in = null;
    private static DataOutputStream out = null;
    static String response = null;
    static FileWriter fstream = null;
    static BufferedWriter bout = null;

    public MvTelnet() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("HH-mm-ss");
        try {
            tc = new TelnetClient();
            bout = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/mnt/javaprograms/ServerConsole/log"+sdf.format(cal.getTime())+".txt"), "UTF-8"));
            TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
            EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
            SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
            try {
                tc.addOptionHandler(ttopt);
                tc.addOptionHandler(echoopt);
                tc.addOptionHandler(gaopt);
            } catch (InvalidTelnetOptionException e) {
                ServerConsole.log(e.getMessage());
            }
            tc.connect("192.168.1.8", 2010);
            in = new DataInputStream(tc.getInputStream());
            out = new DataOutputStream(tc.getOutputStream());
            logon(true);
        } catch (IOException ex) {
            ServerConsole.log(ex.getMessage());
        }
    }

    public static String write(String command) throws IOException {
        command = command + "\n";
        byte[] comm = command.getBytes();
        out.write(comm);
        out.flush();
        response = in.readLine();
        bout.write(response+"\n");
        response = in.readLine();
        bout.write(response+"\n");
        if (response.contains("[] Connect time")) {
            logon(false);
            out.write(comm);
            out.flush();
            response = in.readLine();
            bout.write(response+"\n");
            response = in.readLine();
            bout.write(response+"\n");
        }
        bout.flush();
        return response;
    }

    public static void close() throws IOException {
        write("...\n");
        write("OFF\n");
        tc.disconnect();
    }

    private static void logon(boolean choice) throws IOException {
        String loginString = "JAVA-TRANS\n";
        byte[] logon = loginString.getBytes();
        if (choice == true) {
            response = in.readLine();
            bout.write(response+"\n");
            bout.flush();
            response = in.readLine();
            bout.write(response+"\n");
            bout.flush();
            out.write(logon);
            out.flush();
            response = in.readLine();
            bout.write(response+"\n");
            bout.flush();
            response = in.readLine();
            bout.write(response+"\n");
            bout.flush();
            if (!response.contains("OK")) {
                out.write(logon);
                out.flush();
                response = in.readLine();
                bout.write(response+"\n");
                bout.flush();
                while (!response.contains("OK")) {
                    response = in.readLine();
                    bout.write(response+"\n");
                    bout.flush();
                }
            }
            bout.flush();
        } else {
            out.write(logon);
            out.flush();
            out.write(logon);
            out.flush();
            while (!response.contains("OK")) {
                response = in.readLine();
                bout.write(response+"\n");
                bout.flush();
            }
        }
        bout.flush();
    }
}

我已经找到了 Apaches 通用池库,但我无法弄清楚如何在使用我的 MvTelnet 类作为池对象时正确实现它。commons-pool 是正确的方法吗?如果是,我该如何实施?

编辑: 好的,我根据评论添加了所有代码。我想创建一个包含各种 MvTelnet 对象的池,我的套接字可以向这些对象发送命令。我在 bc 中没有任何池代码,这只是一团糟。

4

1 回答 1

0

如果要创建具有多个连接的客户端-服务器,则必须逐个连接使用一个线程。当客户端请求连接时,添加一个新线程来处理新客户端的输入输出。

编辑:如果需要,您可以使用有限数量的线程,只需创建一个函数,当且仅当有空闲位置时才将新线程分配给客户端。这里的例子

于 2015-01-28T19:00:47.870 回答