1

我的服务器项目分为 6 个不同的类:

  • ServerConnectionManager - 类是所有其他类的中心
  • Connection - 每当客户端连接并启动线程时都会创建此对象
  • ServerListner - 这是侦听用户输入的 Thread 类
  • ServerSender - 这是向一个或多个用户发送消息的类
  • ServerInformation - 这个类包含两个列表,一个是聊天人,一个是连接 这个类还允许您搜索列表以找到特定的人和/或连接
  • ChatPerson - 此对象包含连接到服务器的每个人的用户名

毫无疑问,您现在已经猜到这是一个聊天程序的服务器!

我对你的问题是:

我想在这个项目上使用设计模式(调解器),因此 ServerConnectionManager 包含每个类使用的所有关键方法。例如,将连接添加到 ServerInformation 类中的连接列表。

但是由于 ServerInformation 类不能被称为对象,因为它只有很多方法(函数)并且除了存储和搜索数据之外没有其他实际用途,将其设为静态是个好主意吗?还是我应该坚持计划,让一切都通过 ServerConnectionManager?

这是我的代码示例:

服务器连接管理器

public class ServerConnectionManager {

    private static ServerSocket server;
    private static Socket connection;
    private static ServerInformation ai = new ServerInformation();
    private static boolean connected = false;
    private static final int portNumber = 7070;
    private static int backLog = 100;

    /**
     * This method launches the server (and the application)!
     * @param args
     */
    public static void main(String[] args){
        startServer();
        waitForConnection();
    }


    /**
     *This method sets the serverSocket to portNumber and also adds the backLog.
     */
    private static void startServer() {
        try {
            server = new ServerSocket(portNumber, backLog);
            connected = true;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * This method waits for a connection aslong as the serverSocket is connected.
     * When a new client connects it creates an Object of the connection and starts the individual procedure.
     */
    private static void waitForConnection() {
        while (connected) {
            try {
                connection = server.accept();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Connection c = new Connection(connection);
            addConnection(c);
            waitForConnection();
        }

    }


    public static void closeMe(Socket con) {
        for (Connection conn : ai.getConnectionList()) {
            if (conn.getConnection() == con) {
                ai.getList().remove(ai.getList().indexOf(ai.getChatPersonByConnection(con)));
                ai.getConnectionList().remove(conn);

                System.out.println(ai.getList());
                System.out.println(ai.getConnectionList());
                conn.close();
                break;

            }
        }

    }
    public static void addConnection(Connection con){
        ai.addToConnectionList(con);

    }
    public static void addChatPerson(ChatPerson p){
        ai.add(p);
        System.out.println(ai.getList());
    }



}

联系

public class Connection{
    private Socket connection;
    public Connection(Socket connection){
        this.connection = connection;
        ServerListner cl = new ServerListner(Connection.this);
        cl.start();
    }
    public Socket getConnection(){
        return this.connection;
    }
    public void close() {
        try {
            connection.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


}

服务器监听器

public class ServerListner extends Thread {

    private Socket connection;
    private BufferedReader br;
    private ChatPerson person;
    private Connection con;
    private ServerInformation ai = new ServerInformation();
    private ServerSender sender = new ServerSender();

    public ServerListner(Connection con){
        this.con = con;
        connection = con.getConnection();
        try {
            br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public Socket getConnection(){
        return this.connection;
    }
    public void run(){
        System.out.println(con.getConnection().isConnected());
            try {
                String inString;
                while ((inString = br.readLine()) != null) {
                    if (inString.equalsIgnoreCase("Disconnect")) {
                        System.out.println(inString);
                        break;
                    }else {
                        processInput(inString);
                    }
                }
                ServerConnectionManager.closeMe(connection);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
    public void processInput(String input){
        if (input.equalsIgnoreCase("Connect")) {
            sender.sendMessageToConnection(this.connection, "Accepted");
        }
        if (input.equalsIgnoreCase("UserInformation")) {
            try {
                String username = br.readLine();
                person = new ChatPerson(username, connection);
                ServerConnectionManager.addChatPerson(person);

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (input.equalsIgnoreCase("SearchByCon")) {
            String name = ai.searchByConnection(connection);
            System.out.println(name);
        }

    }
}

服务器发件人

public class ServerSender {
    private PrintWriter pw;
    private ServerInformation ai = new ServerInformation();

    public void addToList(){

    }
    public void sendToAll(String message){
        for (Connection c : ai.getConnectionList()) {
            try {
                pw = new PrintWriter(c.getConnection().getOutputStream());
                pw.print(message);
                pw.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
    /** 
     *
     * @param con
     * @param message
     */

    /*
     * Note - Denne metode gør også at jeg kan hviske til folk!:)
     */
    public void sendMessageToConnection(Socket con, String message){
        try {
            PrintWriter print = new PrintWriter(con.getOutputStream());
            print.println(message);
            print.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }
}

服务器信息

public class ServerInformation{
    private ArrayList<Connection> connectedClients = new ArrayList<Connection>();
    private ArrayList<ChatPerson> list = new ArrayList<ChatPerson>();


    public ArrayList<Connection> getConnectionList(){
        return connectedClients;
    }
    public void addToConnectionList(Connection con){
        connectedClients.add(con);
    }
    public String searchByConnection(Socket myConnection){
        for (ChatPerson p : list) {
            if (p.getConnection() == myConnection) {
                return p.getName();
            }   
        }
        /*
         * If none found!
         */
        return null;
    }

    public ChatPerson getChatPersonByConnection(Socket myConnection){
        for (ChatPerson p : list) {
            if (p.getConnection() == myConnection) {
                return p;
            }
        }
        return null;
    }

    public void add(ChatPerson p){
        list.add(p);
    }

    public void removeByName(String name){
        for (ChatPerson p : list) {
            if (p.getName().equalsIgnoreCase(name)) {
                list.remove(p);     
            }
        }
    }
    public String searchList(String name){
        for (ChatPerson p : list) {
            if (p.getName().equalsIgnoreCase(name)) {
                return p.getName();
            }
        }
        return null;
    }   
    public ArrayList<ChatPerson>getList(){
        return list;
    }

}

聊天人

public class ChatPerson {
    private String chatName;
    private Socket connection;

    /*
     * This is for furture development
     * private Integer adminLevel;
     */

    public ChatPerson(String name, Socket connection){
        this.chatName = name;
        this.connection = connection;
    }
    public void setName(String name){
        this.chatName = name;

    }
    public String getName(){
        return chatName;

    }
    public String toString(){
        return "Username: "+chatName;
    }
    public Socket getConnection(){
        return connection;
    }
}

提前谢谢你,顺便说一句,因为我是一名学生,如果你有时间对我的代码进行评分并就我如何改进提出建议(如果有的话:))

4

1 回答 1

2

您可能是指只有静态方法的类,而不是静态类。静态内部类是不同的(你可以谷歌它)。

在管理器中使用非静态方法的优点:

  • 您可以在测试期间使用 Mockito 等框架轻松地模拟它们。
  • 您可以在重构代码期间将它们拉到某个界面。
  • 使用静态方法不是面向对象的编程,因为此类方法调用与您的类的任何实例(对象)无关。
于 2012-11-17T01:54:40.520 回答