⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chessclient.java

📁 实现了一个网络五子棋的对弈程序
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package client;

import chessface.chatPad;
import chessface.inputPad;
import chessface.userPad;
import chessface.chessPad;
import chessface.controlPad;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;

/*
 * 五子棋客户端框架,实现了动作监听器和键盘监听器
 */

public class chessClient extends Frame implements ActionListener, KeyListener {

    userPad userpad = new userPad();// 用户列表Panel

    chatPad chatpad = new chatPad();// 聊天信息Panel

    controlPad controlpad = new controlPad();// 控制Panel

    chessPad chesspad = new chessPad();// 棋盘Panel

    inputPad inputpad = new inputPad();// 信息输入Panel

    Socket chatSocket;

    DataInputStream in;

    DataOutputStream out;

    String chessClientName = null;

    String host = null;

    int port = 4331;

    boolean isOnChat = false; // 是否在聊天

    boolean isOnChess = false; // 是否在下棋

    boolean isGameConnected = false; // 是否下棋的客户端连接

    boolean isServer = false; // 是否建立游戏的主机

    boolean isClient = false; // 是否加入游戏的客户端

    Panel northPanel = new Panel();

    Panel centerPanel = new Panel();

    Panel eastPanel = new Panel();

    /*
     * 五子棋客户端框架的构造函数。用来初始化一些对象、布局和为按钮添加监听器。
     */
    public chessClient() {
        // 窗口标题
        super("五子棋客户端");
        // 设置布局
        setLayout(new BorderLayout());
        // 获取服务器ip地址
        host = controlpad.inputIP.getText();
        // 右侧的Panel,向里面添加用户列表和聊天信息列表的Panel
        // 设置eastPanel布局
        eastPanel.setLayout(new BorderLayout());
        // 在其上添加用于列表
        eastPanel.add(userpad, BorderLayout.NORTH);
        // 在其上添加聊天信息窗口
        eastPanel.add(chatpad, BorderLayout.CENTER);
        // 设定背景色
        eastPanel.setBackground(new Color(204, 204, 204));

        // 对编辑输出信息窗口添加事件监听器..
        inputpad.inputWords.addKeyListener(this);
        // 设置棋盘Panel所需的服务器地址
        chesspad.host = controlpad.inputIP.getText();
        // 向centerPanel中添加棋盘和用户输入消息panel,并设定背景颜色
        centerPanel.add(chesspad, BorderLayout.CENTER);
        centerPanel.add(inputpad, BorderLayout.SOUTH);
        centerPanel.setBackground(new Color(204, 204, 204));

        // 为controlpad中的按钮们添加事件监听...
        controlpad.connectButton.addActionListener(this);
        controlpad.creatGameButton.addActionListener(this);
        controlpad.joinGameButton.addActionListener(this);
        controlpad.cancelGameButton.addActionListener(this);
        controlpad.exitGameButton.addActionListener(this);

        // 初始设定这几个按钮为非激活状态..
        controlpad.creatGameButton.setEnabled(false);
        controlpad.joinGameButton.setEnabled(false);
        controlpad.cancelGameButton.setEnabled(false);
        // 添加controlpad到northPanel---最上端的panel
        northPanel.add(controlpad, BorderLayout.CENTER);
        northPanel.setBackground(new Color(204, 204, 204));
        // 添加窗口监听器,当窗口关闭时,关闭用于通讯的Socket。
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                if (isOnChat) { //如果聊天连接已建立,则释放
                    try {
                        chatSocket.close();
                    } catch (Exception ed) {
                    }
                }
                if (isOnChess || isGameConnected) { //如果下棋连接已建立,则释放
                    try {
                        chesspad.chessSocket.close();
                    } catch (Exception ee) {
                    }
                }
                System.exit(0);
            }
        });
        // 添加这些panel到frame,组成最终窗口
        add(eastPanel, BorderLayout.EAST);
        add(centerPanel, BorderLayout.CENTER);
        add(northPanel, BorderLayout.NORTH);
        // 设置大小等
        setSize(670, 560);
        setVisible(true);
        setResizable(true);
        validate();
    }

    /**
     * 和服务器建立连接并通信的函数。
     * @return true 如果连接成功, false 如果连接失败..
     */
    public boolean connectServer(String serverIP, int serverPort) throws Exception {
        try {
           // System.out.println("in chessClient#connectServer");
            //建立聊天socket
            chatSocket = new Socket(serverIP, serverPort);
            //由socket得到输入输出流.
            in = new DataInputStream(chatSocket.getInputStream());
            out = new DataOutputStream(chatSocket.getOutputStream());
            //创建线程
            clientThread clientthread = new clientThread(this);
            clientthread.start();
            isOnChat = true;
            return true;
        } catch (IOException ex) {//连接不成功
            chatpad.chatLineArea.setText("chessClient:connectServer:无法连接,建议重新启动程序 \n");
        }
        return false;
    }

    /**
     * 动作监听器,响应按钮点击动作。
     */
    public void actionPerformed(ActionEvent e) {
        ////////////////////////////////////////////////////
        // 如果点击的是“连接主机”按钮,则用获取的服务器主机名连接服务器。
        if (e.getSource() == controlpad.connectButton) {
            host = chesspad.host = controlpad.inputIP.getText();
            try {
                if (connectServer(host, port)) {
                    //连接成功
                    chatpad.chatLineArea.setText("");
                    //连接按钮设置为非激活态..
                    controlpad.connectButton.setEnabled(false);
                    //激活创建,加入游戏按钮
                    controlpad.creatGameButton.setEnabled(true);
                    controlpad.joinGameButton.setEnabled(true);
                    chesspad.statusText.setText("连接成功,请创建游戏或加入游戏");
                }

            } catch (Exception ei) { //连接失败
                chatpad.chatLineArea.setText("controlpad.connectButton:无法连接,建议重新启动程序 \n");
            }
        }
        //////////////////////////////////////////////////////////
        // 如果点击的是“关闭程序”按钮,则关闭正在进行通信的Socekt并退出游戏。
        if (e.getSource() == controlpad.exitGameButton) {
            if (isOnChat) { //如果聊天连接建立则释放
                try {
                    chatSocket.close();
                } catch (Exception ed) {
                }
            }
            if (isOnChess || isGameConnected) {//如果下棋连接建立,则释放
                try {
                    chesspad.chessSocket.close();
                } catch (Exception ee) {
                }
            }
            System.exit(0);

        }
        ///////////////////////////////////////////////////////
        // 如果点击的是“加入游戏”按钮,则先判断选定的加入的目标是否有效。
        // 如果选定的目标为空或正在下棋或为其本身,则认为目标无效。
        if (e.getSource() == controlpad.joinGameButton) {
            // 得到选择的用户
            String selectedUser = userpad.userList.getSelectedItem();
            if (selectedUser == null || selectedUser.startsWith("[inchess]") || selectedUser.equals(chessClientName)) {
                chesspad.statusText.setText("必须先选定一个有效用户");
            } else {
                try {
                    // 如果未建立与服务器的连接,创建连接,设定用户的当前状态。
                    // 此外还要对按钮作一些处理,将“创建连接”按钮和“加入游戏按钮”设为不可用。
                    if (!isGameConnected) {
                        if (chesspad.connectServer(chesspad.host, chesspad.port)) {
                            isGameConnected = true;
                            isOnChess = true;
                            isClient = true;
                            controlpad.creatGameButton.setEnabled(false);
                            controlpad.joinGameButton.setEnabled(false);
                            controlpad.cancelGameButton.setEnabled(true);
                            //向服务器发送用户加入游戏的消息
                            chesspad.chessthread.sendMessage("/joingame " + userpad.userList.getSelectedItem() + " "
                                    + chessClientName);
                        }
                    }
                    // 如果已建立连接,省去建立连接的操作。

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -