This article shares the specific code for Java implementation Goziqi online version for your reference. The specific content is as follows
Requirements Analysis:
For online Goji, the following functions need to be added based on ordinary Goji:
1. Have a server side and a client. After users log in to the server through the client, they can play games with other logged in users.
2. The server supports multiple groups of users to play games at the same time
3. Users can create new games on the server or join created games
4. Users can chat and communicate while playing chess
From the above, we can know the functions that need to be implemented:
・Providing server and client functions
・The server will monitor the client's login status and allow multiple clients to log in
・Users can log in to the server through the client, and then they can see other users of the server currently online and chat with them, etc.
・After logging into the server, users can create a new Gozi game or join the created Gozi game.
・Users can play games with other users like ordinary Goji through the client
According to the function, the network Gochi is divided into 4 modules: namely the user panel module, the board panel module, the Gochi server module, and the Gochi client module
Let's start compiling the user panel module:
1. Develop user list panel
import java.awt.*; /** * Created by Administrator on 2016/11/21. */ //In the initial state, 10 information named "No user" will be added to the list, indicating that the server supports up to 10 users online at the same time.//The list is added to the panel, using the "BorderLayout" layout format public class UserListPad extends Panel{ public List userList=new List(10); public UserListPad(){ setLayout(new BorderLayout()); for(int i=0;i<10;i++){ userList.add(i+"."+"No user"); } add(userList,BorderLayout.CENTER); } } 2. Develop user chat panel
import javax.swing.*; import java.awt.*; /** * Created by Administrator on 2016/11/21. */ //The chat panel is a TextArea view control with a vertical scroll bar. //The TextArea is added to the panel, using the "BorderLayout" layout format. public class UserChatPad extends JPanel{ public JTextArea chatTextArea=new JTextArea("Command Area",18,20); public UserChatPad(){ setLayout(new BorderLayout()); chatTextArea.setAutoscrolls(true); chatTextArea.setLineWrap(true); add(chatTextArea,BorderLayout.CENTER); } } 3. Develop user input panel
import javax.swing.*; import java.awt.*; /** * Created by Administrator on 2016/11/21. */ //The panel contains two view controls//contentInpitted is a TextField control, where users can enter chat information public class UserInputPad extends JPanel{ public JTextField contentInputted = new JTextField("",26); public JComboBox userChoice = new JComboBox(); public UserInputPad(){ setLayout(new FlowLayout(FlowLayout.LEFT)); for(int i=0;i<50;i++){ userChoice.addItem(i+"."+"No user"); } userChoice.setSize(60,24); add(userChoice); add(contentInputted); } } 4. Develop user operation panel
import javax.swing.*; import java.awt.*; /** * Created by Administrator on 2016/11/21. */ public class UserControlPad extends JPanel { public JLabel ipLabel = new JLabel("IP",JLabel.LEFT); public JTextField ipInputted = new JTextField("localhost",10); public JButton connectButton = new JButton("Connect to server"); public JButton createButton = new JButton("Create game"); public JButton joinButton = new JButton("Join game"); public JButton cancelButton = new JButton("Give up game"); public JButton exitButton = new JButton("Exit game"); public UserControlPad(){ setLayout(new FlowLayout(FlowLayout.LEFT)); setBackground(Color.LIGHT_GRAY); add(ipLabel); add(ipInputted); add(connectButton); add(createButton); add(joinButton); add(cancelButton); add(exitButton); } } Start developing the board panel module below
1. Develop black chess
import java.awt.*; /** * Created by Administrator on 2016/11/21. */ public class FIRPointBlack extends Canvas { FIRPad padBelonged; // The board to which the black chess belongs public FIRPointBlack(FIRPad padBelonged) { setSize(20, 20); // Set the chess piece size this.padBelonged = padBelonged; } public void paint(Graphics g) { // Draw chess piece g.setColor(Color.black); g.fillOval(0, 0, 14, 14); } } 2. Develop white chess category
import java.awt.*; /** * Created by Administrator on 2016/11/21. */ public class FIRPointWhite extends Canvas{ FIRPad padBelonged; // The board to which the white chess belongs public FIRPointWhite(FIRPad padBelonged) { setSize(20, 20); this.padBelonged = padBelonged; } public void paint(Graphics g) { // Draw chess pieces g.setColor(Color.white); g.fillOval(0, 0, 14, 14); } } 3. Develop a chessboard panel
import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import javax.swing.JTextField; /** * Created by Administrator on 2016/11/21. */ public class FIRPad extends Panel implements MouseListener,ActionListener{ // Can the mouse be used public boolean isMouseEnabled = false; // Whether to win public boolean isWinned = false; // Whether to play chess public boolean isGaming = false; // x-axis coordinate bits of the chess piece public int chessX_POS = -1; // y-axis coordinate bits of the chess piece public int chessY_POS = -1; // color of the chess piece public int chessColor = 1; // black x-axis coordinate bit array public int chessBlack_XPOS[] = new int[200]; // black y-axis coordinate bit array public int chessBlack_YPOS[] = new int[200]; // white y-axis coordinate bit array public int chessWhite_XPOS[] = new int[200]; // White chess y-axis coordinate digit array public int chessWhite_YPOS[] = new int[200]; // Number of black chess public int chessBlackCount = 0; // Number of white chess public int chessWhiteCount = 0; // Number of black chess wins public int chessBlackVicTimes = 0; // Number of white chess wins public int chessWhiteVicTimes = 0; // Number of white chess wins public int chessWhiteVicTimes = 0; // Sleeve interface public Socket chessSocket; public DataInputStream inputData; public DataOutputStream outputData; public String chesSelfName = null; public String chessPeerName = null; public String host = null; public int port = 4331; public TextField statusText = new TextField("Please connect to the server!"); public FIRThread firThread = new FIRThread(this); public FIRPad() { setSize(440, 440); setLayout(null); setBackground(Color.LIGHT_GRAY); addMouseListener(this); add(statusText); statusText.setBounds(new Rectangle(40, 5, 360, 24)); statusText.setEditable(false); } // Connect to the host public boolean connectServer(String ServerIP, int ServerPort) throws Exception { try { // Get the host port chessSocket = new Socket(ServerIP, ServerPort); // Get the input stream inputData = new DataInputStream(chessSocket.getInputStream()); // get outputData = new DataOutputStream(chessSocket.getOutputStream()); firThread.start(); return true; } catch (IOException ex) { statusText.setText("Connection failed! /n"); } return false; } // Set the board status when winning public void setVicStatus(int vicChessColor) { // Clear the board this.removeAll(); // Set the black chess position to zero for (int i = 0; i <= chessBlackCount; i++) { chessBlack_XPOS[i] = 0; chessBlack_YPOS[i] = 0; } // Set the position of the white chess to zero for (int i = 0; i <= chessWhiteCount; i++) { chessWhite_XPOS[i] = 0; chessWhite_YPOS[i] = 0; } // Clear the number of black chess on the board chessBlackCount = 0; // Clear the number of white chess on the board chessWhiteCount = 0; add(statusText); statusText.setBounds(40, 5, 360, 24); if (vicChessColor == 1) { // Black Chess wins chessBlackVicTimes++; statusText.setText("Black, black:white" + chessBlackVicTimes + ":" + chessWhiteVicTimes + ", game restart, wait for white..."); } else if (vicChessColor == -1) { // White Chess wins chessWhiteVicTimes++; statusText.setText("Black:white" + chessBlackVicTimes + ":" + chessWhiteVicTimes + ", game restart, wait for black..."); } } // Get the position of the specified chess piece public void setLocation(int xPos, int yPos, int chessColor) { if (chessColor == 1) { // When the chess piece is black, chessBlack_XPOS[chessBlackCount] = xPos * 20; chessBlack_YPOS[chessBlackCount] = yPos * 20; chessBlackCount++; } else if (chessColor == -1) { // When the chess piece is white, chessWhite_XPOS[chessWhiteCount] = xPos * 20; chessWhiteCount++; } } // Determine whether the current state is a winning state public boolean checkVicStatus(int xPos, int yPos, int chessColor) { int chessLinkedCount = 1; // Number of connected chessLinkedCompare = 1; // Used to compare whether you want to continue traversing a piece int chessToCompareIndex = 0; // The index position of the piece to be compared int closeGrid = 1; // The position of the adjacent grid if (chessColor == 1) { // ChessLinkedCount = 1; // If the chess piece itself is counted, the initial number of connections is 1 //Each pair of for loop statements below is a group, because the position of the next period can be in the middle rather than at both ends for (closeGrid = 1; closeGrid <= 4; closeGrid++) { //Transipate through 4 adjacent grids for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { //Transipate through all black chess pieces on the board if (((xPos + closeGrid) * 20 == chessBlack_XPOS[chessToCompareIndex]) && ((yPos * 20) == chessBlack_YPOS[chessToCompareIndex])) { // Determine whether the four chess pieces on the right of the currently played chessLinkedCount = chessLinkedCount + 1; // Add 1 to the number of connections if (chessLinkedCount == 5) { // When the five pieces are connected, the victory returns true; } } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else {// If there is a chess piece in the middle that is not black, it will enter this branch, and there is no need to traverse break again at this time; } } for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if (((xPos - closeGrid) * 20 == chessBlack_XPOS[chessToCompareIndex]) && (yPos * 20 == chessBlack_YPOS[chessToCompareIndex])) { // Determine whether the four chess pieces on the left of the currently playing chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } // When entering a new set of for loops, reset the number of connections, etc. chessLinkedCount = 1; chessLinkedCompare = 1; for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if ((xPos * 20 == chessBlack_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * 20 == chessBlack_YPOS[chessToCompareIndex])) { // Determine whether the top 4 pieces of the currently playing chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if ((xPos * 20 == chessBlack_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * 20 == chessBlack_YPOS[chessToCompareIndex])) { // Determine whether the four pieces below the currently played chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } chessLinkedCount = 1; chessLinkedCompare = 1; for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if ((((xPos - closeGrid) * 20 == chessBlack_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * 20 == chessBlack_YPOS[chessToCompareIndex])) { // Determine whether the four chess pieces in the upper left direction of the currently playing chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if (((xPos + closeGrid) * 20 == chessBlack_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * 20 == chessBlack_YPOS[chessToCompareIndex])) { // Determine whether the four chess pieces in the lower right direction of the current chess piece are black chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } chessLinkedCount = 1; chessLinkedCompare = 1; for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if (((xPos + closeGrid) * 20 == chessBlack_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * 20 == chessBlack_YPOS[chessToCompareIndex])) { // Determine whether the four chess pieces in the upper right direction of the current chess piece are black chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if (((xPos - closeGrid) * 20 == chessBlack_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * 20 == chessBlack_YPOS[chessToCompareIndex])) { // Determine whether the four chess pieces in the lower left direction of the current chess piece are black chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } } else if (chessColor == -1) { // ChessLinkedCount = 1; for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos + closeGrid) * 20 == chessWhite_XPOS[chessToCompareIndex]) && (yPos * 20 == chessWhite_YPOS[chessToCompareIndex])) {// Determine whether the four pieces on the right of the currently playing chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos - closeGrid) * 20 == chessWhite_XPOS[chessToCompareIndex]) && (yPos * 20 == chessWhite_YPOS[chessToCompareIndex])) {// Determine whether the four pieces on the left of the currently playing chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } chessLinkedCount = 1; chessLinkedCompare = 1; for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if ((xPos * 20 == chessWhite_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * 20 == chessWhite_YPOS[chessToCompareIndex])) {// Determine whether the top 4 pieces of the currently playing chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if ((xPos * 20 == chessWhite_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * 20 == chessWhite_YPOS[chessToCompareIndex])) {// Determine whether the four pieces below the currently played chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } chessLinkedCount = 1; chessLinkedCompare = 1; for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos - closeGrid) * 20 == chessWhite_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * 20 == chessWhite_YPOS[chessToCompareIndex])) {// Determine whether all the 4 pieces in the upper left direction of the current chess piece are white chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos + closeGrid) * 20 == chessWhite_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * 20 == chessWhite_YPOS[chessToCompareIndex])) {// Determine whether the four chess pieces in the lower right direction of the current chess piece are white chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } chessLinkedCount = 1; chessLinkedCompare = 1; for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos + closeGrid) * 20 == chessWhite_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * 20 == chessWhite_YPOS[chessToCompareIndex])) {// Determine whether all the 4 pieces in the upper right direction of the current chess piece are white chessLinkedCount++; if (chessLinkedCount == 5) { return true; } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos - closeGrid) * 20 == chessWhite_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * 20 == chessWhite_YPOS[chessToCompareIndex])) {// Determine whether the four pieces in the lower left direction of the currently playing chessLinkedCount++; if (chessLinkedCount == 5) { return (true); } } } } if (chessLinkedCount == (chessLinkedCompare + 1)) { chessLinkedCompare++; } else { break; } } } return false; } // Draw the chessboard public void paint(Graphics g) { for (int i = 40; i <= 380; i = i + 20) { g.drawLine(40, i, 400, i); } g.drawLine(40, 400, 400, 400); for (int j = 40; j <= 380; j = j + 20) { g.drawLine(j, 40, j, 400); } g.drawLine(400, 40, 400, 400); g.fillOval(97, 97, 6, 6); g.fillOval(337, 97, 6, 6); g.fillOval(97, 337, 6, 6); g.fillOval(337, 337, 6, 6); g.fillOval(337, 337, 6, 6); g.fillOval(217, 217, 6, 6); } // Draw chesspawn public void paintFirPoint(int xPos, int yPos, int chessColor) { FIRPointBlack firPBlack = new FIRPointBlack(this); FIRPointWhite firPWhite = new FIRPointWhite(this); if (chessColor == 1 && isMouseEnabled) { // Black Chess// Set the position of the chess piece setLocation(xPos, yPos, chessColor); // Get the current situation status isWinned = checkVicStatus(xPos, yPos, chessColor); if (isWinned == false) { // Non-win state firThread.sendMessage("/" + chessPeerName + " /chess " + xPos + " " + yPos + " " + chessColor); this.add(firPBlack); // Add chess pieces to the board firPBlack.setBounds(xPos * 20 - 7, yPos * 20 - 7, 16, 16); // Set the chess boundary statusText.setText("black(" + chessBlackCount + "step)" + xPos + " " + yPos + ", it's the turn of white square."); isMouseEnabled = false; // Set the mouse to unavailable} else { // win status firThread.sendMessage("/" + chessPeerName + " /chess " + xPos + " " + yPos + " " + chessColor); this.add(firPBlack); firPBlack.setBounds(xPos * 20 - 7, yPos * 20 - 7, 16, 16); setVicStatus(1); // Call the victory method, and the parameter passed as black chess victory isMouseEnabled = false; } } else if (chessColor == -1 && isMouseEnabled) { // White chess setLocation(xPos, yPos, chessColor); isWinned = checkVicStatus(xPos, yPos, chessColor); if (isWinned == false) { firThread.sendMessage("/" + chessPeerName + " /chess " + xPos + " " + yPos + " " + chessColor); this.add(firPWhite); firPWhite.setBounds(xPos * 20 - 7, yPos * 20 - 7, 16, 16); statusText.setText("white(thread" + chessWhiteCount + "step)" + xPos + " " + yPos + ",It's Black's turn."); isMouseEnabled = false; } else { firThread.sendMessage("/" + chessPeerName + " /chess " + xPos + " " + yPos + " " + chessColor); this.add(firPWhite); firPWhite.setBounds(xPos * 20 - 7, yPos * 20 - 7, 16, 16); setVicStatus(-1); // Call the victory method, and the parameter passed in isMouseEnabled = false; } } } // Draw the network chessboard public void paintNetFirPoint(int xPos, int yPos, int chessColor) { FIRPointBlack firPBlack = new FIRPointBlack(this); FIRPointWhite firPWhite = new FIRPointWhite(this); setLocation(xPos, yPos, chessColor); if (chessColor == 1) { isWinned = checkVicStatus(xPos, yPos, chessColor); if (isWinned == false) { this.add(firPBlack); firPBlack.setBounds(xPos * 20 - 7, yPos * 20 - 7, 16, 16); statusText.setText("black(thread" + chessBlackCount + "step)" + xPos + " " + yPos + ",It's the White Square."); isMouseEnabled = true; } else { firThread.sendMessage("/" + chessPeerName + " /victory " + chessColor);//djr this.add(firPBlack); firPBlack.setBounds(xPos * 20 - 7, yPos * 20 - 7, 16, 16); setVicStatus(1); isMouseEnabled = true; } } else if (chessColor == -1) { isWinned = checkVicStatus(xPos, yPos, chessColor); if (isWinned == false) { this.add(firPWhite); firPWhite.setBounds(xPos * 20 - 7, yPos * 20 - 7, 16, 16); statusText.setText("White("+chessWhiteCount + "step)" + xPos + " " + yPos + ",It's Black's turn."); isMouseEnabled = true; } else { firThread.sendMessage("/" + chessPeerName + " /victory " + chessColor); this.add(firPWhite); firPWhite.setBounds(xPos * 20 - 7, yPos * 20 - 7, 16, 16); setVicStatus(-1); isMouseEnabled = true; } } } // Capture chess event public void mousePressed(MouseEvent e) { if (e.getModifiers() == InputEvent.BUTTON1_MASK) { chessX_POS = (int) e.getX(); chessY_POS = (int) e.getY(); int a = (chessX_POS + 10) / 20, b = (chessY_POS + 10) / 20; if (chessX_POS / 20 < 2 || chessY_POS / 20 < 2 || chessX_POS / 20 > 19 || chessY_POS / 20 > 19) { // No action is performed when the chess position is incorrect} else { paintFirPoint(a, b, chessColor); // Draw chess pieces} } } public void mouseReleased(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mouseClicked(MouseEvent e){} public void actionPerformed(ActionEvent e){} } 4. Develop chessboard threads
import java.util.StringTokenizer; import java.io.IOException; /** * Created by Administrator on 2016/11/21. */ public class FIRThread extends Thread{ FIRPad currPad; // The current thread's chess board public FIRThread(FIRPad currPad) { this.currPad = currPad; } // Process the obtained information public void dealWithMsg(String msgReceived) { if (msgReceived.startsWith("/chess ")) { // The information received is chess StringTokenizer userMsgToken = new StringTokenizer(msgReceived, " "); // The array of chess pieces information and 0 indexes are: x coordinate; 1 index bit: y coordinate; 2 index bit: chessInfo = { "-1", "-1", "0" }; int i = 0; // Flag bit String chessInfoToken; while (userMsgToken.hasMoreTokens()) { chessInfoToken = (String) userMsgToken.nextToken(" "); if (i >= 1 && i <= 3) { chessInfo[i - 1] = chessInfoToken; } i++; } currPad.paintNetFirPoint(Integer.parseInt(chessInfo[0]), Integer .parseInt(chessInfo[1]), Integer.parseInt(chessInfo[2])); } else if (msgReceived.startsWith("/yourname ")) { // The message received is renamed currPad.chessSelfName = msgReceived.substring(10); } else if (msgReceived.equals("/error")) { // The error message received is currPad.statusText.setText("The user does not exist, please re-join!"); } } // Send the message public void sendMessage(String sndMessage) { try { currPad.outputData.writeUTF(sndMessage); } catch (Exception ea) { ea.printStackTrace();; } } public void run() { String msgReceived = ""; try { while (true) { // Wait for information input msgReceived = currPad.inputData.readUTF(); dealWithMsg(msgReceived); } } catch (IOException es){} } } Start developing the server module below
1. Develop server information panel
import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Label; import java.awt.Panel; import java.awt.TextArea; import javax.swing.JLabel; /** * Created by Administrator on 2016/11/21. */ public class ServerMsgPanel extends Panel { public TextArea msgTextArea = new TextArea("", 22, 50, TextArea.SCROLLBARS_VERTICAL_ONLY); public JLabel statusLabel = new JLabel("Current connections:", Label.LEFT); public Panel msgPanel = new Panel(); public Panel statusPanel = new Panel(); public ServerMsgPanel() { setSize(350, 300); setBackground(Color.LIGHT_GRAY); setLayout(new BorderLayout()); msgPanel.setLayout(new FlowLayout()); msgPanel.setSize(210, 210); statusPanel.setLayout(new BorderLayout()); statusPanel.setSize(210, 50); msgPanel.add(msgTextArea); statusPanel.add(statusLabel, BorderLayout.WEST); add(msgPanel, BorderLayout.CENTER); add(statusPanel, BorderLayout.NORTH); } } 2. Develop server process
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.Enumeration; import java.util.Hashtable; import java.util.StringTokenizer; /** * Created by Administrator on 2016/11/21. */ public class FIRServerThread extends Thread{ Socket clientSocket; // Save client socket information Hashtable clientDataHash; // Save the Hash Hashtable clientNameHash corresponding to the client port and the output stream; // Save the Hash Hashtable chessPeerHash corresponding to the client socket and the client name; // Save the Hash ServerMsgPanel corresponding to the game creator and the game joiner; boolean isClientClosed = false; public FIRServerThread(Socket clientSocket, Hashtable clientDataHash, Hashtable clientNameHash, Hashtable chessPeerHash, ServerMsgPanel server) { this.clientSocket = clientSocket; this.clientDataHash = clientDataHash; this.clientNameHash = clientNameHash; this.chessPeerHash = chessPeerHash; this.serverMsgPanel = server; } public void dealWithMsg(String msgReceived) { String clientName; String peerName; if (msgReceived.startsWith("/")) { if (msgReceived.equals("/list")) { // The received information is to update the user list Feedback(getUserList()); } else if (msgReceived.startsWith("/creatgame [inchess]")) { // The message received is to create the game String gameCreaterName = msgReceived.substring(20); // Get the server name synchronized (clientNameHash) { // Put the user port in the user list clientNameHash.put(clientSocket, msgReceived.substring(11)); } synchronized (chessPeerHash) { // Set the host to the wait state chessPeerHash.put(gameCreaterName, "wait"); } Feedback("/yourname " + clientNameHash.get(clientSocket)); sendGamePeerMsg(gameCreaterName, "/OK"); sendPublicMsg(getUserList()); } else if (msgReceived.startsWith("/joingame ")) { // The message received is when joining the game StringTokenizer userTokens = new StringTokenizer(msgReceived, " "); String userToken; String gameCreatorName; String gamePaticipantName; String[] playerNames = { "0", "0" }; int nameIndex = 0; while (userTokens.hasMoreTokens()) { userToken = (String) userTokens.nextToken(" "); if (nameIndex >= 1 && nameIndex <= 2) { playerNames[nameIndex - 1] = userToken; // Get the player's life} nameIndex++; } gameCreatorName = playerNames[0]; gamePaticipantName = playerNames[1]; if (chessPeerHash.containsKey(gameCreatorName) && chessPeerHash.get(gameCreatorName).equals("wait")) { // The game has been created synchronized (clientNameHash) { // Add the corresponding clientNameHash.put(clientSocket, ("[inchess]" + gamePaticipantName)); } synchronized (chessPeerHash) { // Add or modify the corresponding chessPeerHash.put(gameCreatorName, gamePaticipantName); } sendPublicMsg(getUserList()); // Send message to the game joiner sendGamePeerMsg(gamePaticipantName, ("/peer " + "[inchess]" + gameCreatorName)); // Send the game to the game creator sendGamePeerMsg(gameCreatorName, ("/peer " + "[inchess]" + gamePaticipantName)); } else { // If the game is not created, the game is refused to be added sendGamePeerMsg(gamePaticipantName, "/reject"); try { closeClient(); } catch (Exception ez) { ez.printStackTrace(); } } } else if (msgReceived.startsWith("/[inchess]")) { // The message received is int firstLocation = 0, lastLocation; lastLocation = msgReceived.indexOf(" ", 0); peerName = msgReceived.substring((firstLocation + 1), lastLocation); msgReceived = msgReceived.substring((lastLocation + 1)); if (sendGamePeerMsg(peerName, msgReceived)) { Feedback("/error"); } } else if (msgReceived.startsWith("/giveup ")) { // The message received is when you give up the game String chessClientName = msgReceived.substring(8); if (chessPeerHash.containsKey(chessClientName) && !((String) chessPeerHash.get(chessClientName)) .equals("wait")) { // The winner is the game joiner, send the victory message sendGamePeerMsg((String) chessPeerHash.get(chessClientName), "/youwin"); synchronized (chessPeerHash) { // Delete the user quit the game chessPeerHash.remove(chessClientName); } } if (chessPeerHash.containsValue(chessClientName)) { // The winner is the game creator and sends the victory message sendGamePeerMsg((String) getHashKey(chessPeerHash, chessClientName), "/youwin"); synchronized (chessPeerHash) {// Delete the user quit the game chessPeerHash.remove((String) getHashKey(chessPeerHash, chessClientName)); } } } else { // When the received information is other information int lastLocation = msgReceived.indexOf(" ", 0); if (lastLocation == -1) { Feedback("Invalid command"); return; } } } else { msgReceived = clientNameHash.get(clientSocket) + ">" + msgReceived; serverMsgPanel.msgTextArea.append(msgReceived + "/n"); sendPublicMsg(msgReceived); serverMsgPanel.msgTextArea.setCaretPosition(serverMsgPanel.msgTextArea.getText() .length()); } } // Send public void sendPublicMsg(String publicMsg) { synchronized (clientDataHash) { for (Enumeration enu = clientDataHash.elements(); enu .hasMoreElements();) { DataOutputStream outputData = (DataOutputStream) enu.nextElement(); try { outputData.writeUTF(publicMsg); } catch (IOException es) { es.printStackTrace(); } } } } } // Send information to the user in the specified game public boolean sendGamePeerMsg(String gamePeerTarget, String gamePeerMsg) { for (Enumeration enu = clientDataHash.keys(); enu.hasMoreElements();) { // traverse to obtain the socket interface of the user in the game Socket userClient = (Socket) enu.nextElement(); if (gamePeerTarget.equals((String) clientNameHash.get(userClient)) && !gamePeerTarget.equals((String) clientNameHash .get(clientSocket))) { // synchronized (clientDataHash) { // Create output stream DataOutputStream peerOutData = (DataOutputStream) clientDataHash .get(userClient); try { // Send information peerOutData.writeUTF(gamePeerMsg); } catch (IOException es) { es.printStackTrace(); } } return false; } } return true; } // Send feedback information to the person connected to the host public void Feedback(String feedBackMsg) { synchronized (clientDataHash) { DataOutputStream outputData = (DataOutputStream) clientDataHash .get(clientSocket); try { outputData.writeUTF(feedBackMsg); } catch (Exception eb) { eb.printStackTrace(); } } } // Get the user list public String getUserList() { String userList = "/userlist"; for (Enumeration enu = clientNameHash.elements(); enu.hasMoreElements();) { userList = userList + " " + (String) enu.nextElement(); } return userList; } // Get the corresponding key from the Hashtable according to the value value public Object getHashKey(Hashtable targetHash, Object hashValue) { Object hashKey; for (Enumeration enu = targetHash.keys(); enu.hasMoreElements();) { hashKey = (Object) enu.nextElement(); if (hashValue.equals((Object) targetHash.get(hashKey))) return hashKey; } return null; } // Method executed when just connected to the host public void sendInitMsg() { sendPublicMsg(getUserList()); Feedback("/yourname " + (String) clientNameHash.get(clientSocket)); Feedback("Java 五子棋客户端"); Feedback("/list --更新用户列表"); Feedback("/<username> <talk> --私聊"); Feedback("注意:命令必须对所有用户发送"); } public void closeClient() { serverMsgPanel.msgTextArea.append("用户断开连接:" + clientSocket + "/n"); synchronized (chessPeerHash) { //如果是游戏客户端主机if (chessPeerHash.containsKey(clientNameHash.get(clientSocket))) { chessPeerHash.remove((String) clientNameHash.get(clientSocket)); } if (chessPeerHash.containsValue(clientNameHash.get(clientSocket))) { chessPeerHash.put((String) getHashKey(chessPeerHash, (String) clientNameHash.get(clientSocket)), "tobeclosed"); } } synchronized (clientDataHash) { // 删除客户数据clientDataHash.remove(clientSocket); } synchronized (clientNameHash) { // 删除客户数据clientNameHash.remove(clientSocket); } sendPublicMsg(getUserList()); serverMsgPanel.statusLabel.setText("当前连接数:" + clientDataHash.size()); try { clientSocket.close(); } catch (IOException exx) { exx.printStackTrace(); } isClientClosed = true; } public void run() { DataInputStream inputData; synchronized (clientDataHash) { serverMsgPanel.statusLabel.setText("当前连接数:" + clientDataHash.size()); } try { // 等待连接到主机的信息inputData = new DataInputStream(clientSocket.getInputStream()); sendInitMsg(); while (true) { String message = inputData.readUTF(); dealWithMsg(message); } } catch (IOException esx){} finally { if (!isClientClosed) { closeClient(); } } } } 3.开发服务器端
import java.io.*; import java.net.*; import java.awt.*; import java.util.*; import java.awt.event.*; import javax.swing.JButton; /** * Created by Administrator on 2016/11/21. */ public class FIRServer extends Frame implements ActionListener{ JButton clearMsgButton = new JButton("清空列表"); JButton serverStatusButton = new JButton("服务器状态"); JButton closeServerButton = new JButton("关闭服务器"); Panel buttonPanel = new Panel(); ServerMsgPanel serverMsgPanel = new ServerMsgPanel(); ServerSocket serverSocket; Hashtable clientDataHash = new Hashtable(50); //将客户端套接口和输出流绑定Hashtable clientNameHash = new Hashtable(50); //将客户端套接口和客户名绑定Hashtable chessPeerHash = new Hashtable(50); //将游戏创建者和游戏加入者绑定public FIRServer() { super("Java 五子棋服务器"); setBackground(Color.LIGHT_GRAY); buttonPanel.setLayout(new FlowLayout()); clearMsgButton.setSize(60, 25); buttonPanel.add(clearMsgButton); clearMsgButton.addActionListener(this); serverStatusButton.setSize(75, 25); buttonPanel.add(serverStatusButton); serverStatusButton.addActionListener(this); closeServerButton.setSize(75, 25); buttonPanel.add(closeServerButton); closeServerButton.addActionListener(this); add(serverMsgPanel, BorderLayout.CENTER); add(buttonPanel, BorderLayout.SOUTH); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); pack(); setVisible(true); setSize(400, 300); setResizable(false); validate(); try { createServer(4331, serverMsgPanel); } catch (Exception e) { e.printStackTrace(); } } // 用指定端口和面板创建服务器public void createServer(int port, ServerMsgPanel serverMsgPanel) throws IOException { Socket clientSocket; // 客户端套接口long clientAccessNumber = 1; // 连接到主机的客户数量this.serverMsgPanel = serverMsgPanel; // 设定当前主机try { serverSocket = new ServerSocket(port); serverMsgPanel.msgTextArea.setText("服务器启动于:" + InetAddress.getLocalHost() + ":" //djr + serverSocket.getLocalPort() + "/n"); while (true) { // 监听客户端套接口的信息clientSocket = serverSocket.accept(); serverMsgPanel.msgTextArea.append("已连接用户:" + clientSocket + "/n"); // 建立客户端输出流DataOutputStream outputData = new DataOutputStream(clientSocket .getOutputStream()); // 将客户端套接口和输出流绑定clientDataHash.put(clientSocket, outputData); // 将客户端套接口和客户名绑定clientNameHash .put(clientSocket, ("新玩家" + clientAccessNumber++)); // 创建并运行服务器端线程FIRServerThread thread = new FIRServerThread(clientSocket, clientDataHash, clientNameHash, chessPeerHash, serverMsgPanel); thread.start(); } } catch (IOException ex) { ex.printStackTrace(); } } public void actionPerformed(ActionEvent e) { if (e.getSource() == clearMsgButton) { // 清空服务器信息serverMsgPanel.msgTextArea.setText(""); } if (e.getSource() == serverStatusButton) { // 显示服务器信息try { serverMsgPanel.msgTextArea.append("服务器信息:" + InetAddress.getLocalHost() + ":" + serverSocket.getLocalPort() + "/n"); } catch (Exception ee) { ee.printStackTrace(); } } if (e.getSource() == closeServerButton) { // 关闭服务器System.exit(0); } } public static void main(String args[]) { FIRServer firServer = new FIRServer(); } }下面开始编写客户端模块
1.开发客户端
import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import javax.swing.JFrame; import djr.chess.gui.UserChatPad; import djr.chess.gui.UserControlPad; import djr.chess.gui.UserInputPad; import djr.chess.gui.UserListPad; import djr.chess.pad.FIRPad; /** * Created by Administrator on 2016/11/21. */ public class FIRClient extends Frame implements ActionListener,KeyListener { // 客户端套接口Socket clientSocket; // 数据输入流DataInputStream inputStream; // 数据输出流DataOutputStream outputStream; // 用户名String chessClientName = null; // 主机地址String host = null; // 主机端口int port = 4331; // 是否在聊天boolean isOnChat = false; // 是否在下棋boolean isOnChess = false; // 游戏是否进行中boolean isGameConnected = false; // 是否为游戏创建者boolean isCreator = false; // 是否为游戏加入者boolean isParticipant = false; // 用户列表区UserListPad userListPad = new UserListPad(); // 用户聊天区UserChatPad userChatPad = new UserChatPad(); // 用户操作区UserControlPad userControlPad = new UserControlPad(); // 用户输入区UserInputPad userInputPad = new UserInputPad(); // 下棋区FIRPad firPad = new FIRPad(); // 面板区Panel southPanel = new Panel(); Panel northPanel = new Panel(); Panel centerPanel = new Panel(); Panel eastPanel = new Panel(); // 构造方法,创建界面public FIRClient() { super("Java 五子棋客户端"); setLayout(new BorderLayout()); host = userControlPad.ipInputted.getText(); eastPanel.setLayout(new BorderLayout()); eastPanel.add(userListPad, BorderLayout.NORTH); eastPanel.add(userChatPad, BorderLayout.CENTER); eastPanel.setBackground(Color.LIGHT_GRAY); userInputPad.contentInputted.addKeyListener(this); firPad.host = userControlPad.ipInputted.getText(); centerPanel.add(firPad, BorderLayout.CENTER); centerPanel.add(userInputPad, BorderLayout.SOUTH); centerPanel.setBackground(Color.LIGHT_GRAY); userControlPad.connectButton.addActionListener(this); userControlPad.createButton.addActionListener(this); userControlPad.joinButton.addActionListener(this); userControlPad.cancelButton.addActionListener(this); userControlPad.exitButton.addActionListener(this); userControlPad.createButton.setEnabled(false); userControlPad.joinButton.setEnabled(false); userControlPad.cancelButton.setEnabled(false); southPanel.add(userControlPad, BorderLayout.CENTER); southPanel.setBackground(Color.LIGHT_GRAY); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { if (isOnChat) { // 聊天中try { // 关闭客户端套接口clientSocket.close(); } catch (Exception ed){} } if (isOnChess || isGameConnected) { // 下棋中try { // 关闭下棋端口firPad.chessSocket.close(); } catch (Exception ee){} } System.exit(0); } }); add(eastPanel, BorderLayout.EAST); add(centerPanel, BorderLayout.CENTER); add(southPanel, BorderLayout.SOUTH); pack(); setSize(670, 560); setVisible(true); setResizable(false); this.validate(); } // 按指定的IP地址和端口连接到服务器public boolean connectToServer(String serverIP, int serverPort) throws Exception { try { // 创建客户端套接口clientSocket = new Socket(serverIP, serverPort); // 创建输入流inputStream = new DataInputStream(clientSocket.getInputStream()); // 创建输出流outputStream = new DataOutputStream(clientSocket.getOutputStream()); // 创建客户端线程FIRClientThread clientthread = new FIRClientThread(this); // 启动线程,等待聊天信息clientthread.start(); isOnChat = true; return true; } catch (IOException ex) { userChatPad.chatTextArea .setText("不能连接!/n"); } return false; } // 客户端事件处理public void actionPerformed(ActionEvent e) { if (e.getSource() == userControlPad.connectButton) { // 连接到主机按钮单击事件host = firPad.host = userControlPad.ipInputted.getText(); // 取得主机地址try { if (connectToServer(host, port)) { // 成功连接到主机时,设置客户端相应的界面状态userChatPad.chatTextArea.setText(""); userControlPad.connectButton.setEnabled(false); userControlPad.createButton.setEnabled(true); userControlPad.joinButton.setEnabled(true); firPad.statusText.setText("连接成功,请等待!"); } } catch (Exception ei) { userChatPad.chatTextArea .setText("不能连接!/n"); } } if (e.getSource() == userControlPad.exitButton) { // 离开游戏按钮单击事件if (isOnChat) { // 若用户处于聊天状态中try { // 关闭客户端套接口clientSocket.close(); } catch (Exception ed){} } if (isOnChess || isGameConnected) { // 若用户处于游戏状态中try { // 关闭游戏端口firPad.chessSocket.close(); } catch (Exception ee){} } System.exit(0); } if (e.getSource() == userControlPad.joinButton) { // 加入游戏按钮单击事件String selectedUser = (String)userListPad.userList.getSelectedItem(); // 取得要加入的游戏if (selectedUser == null || selectedUser.startsWith("[inchess]") || selectedUser.equals(chessClientName)) { // 若未选中要加入的用户,或选中的用户已经在游戏,则给出提示信息firPad.statusText.setText("必须选择一个用户!"); } else { // 执行加入游戏的操作try { if (!isGameConnected) { // 若游戏套接口未连接if (firPad.connectServer(firPad.host, firPad.port)) { // 若连接到主机成功isGameConnected = true; isOnChess = true; isParticipant = true; userControlPad.createButton.setEnabled(false); userControlPad.joinButton.setEnabled(false); userControlPad.cancelButton.setEnabled(true); firPad.firThread.sendMessage("/joingame " + (String)userListPad.userList.getSelectedItem() + " " + chessClientName); } } else { // 若游戏端口连接中isOnChess = true; isParticipant = true; userControlPad.createButton.setEnabled(false); userControlPad.joinButton.setEnabled(false); userControlPad.cancelButton.setEnabled(true); firPad.firThread.sendMessage("/joingame " + (String)userListPad.userList.getSelectedItem() + " " + chessClientName); } } catch (Exception ee) { isGameConnected = false; isOnChess = false; isParticipant = false; userControlPad.createButton.setEnabled(true); userControlPad.joinButton.setEnabled(true); userControlPad.cancelButton.setEnabled(false); userChatPad.chatTextArea .setText("不能连接: /n" + ee); } } } if (e.getSource() == userControlPad.createButton) { // 创建游戏按钮单击事件try { if (!isGameConnected) { // 若游戏端口未连接if (firPad.connectServer(firPad.host, firPad.port)) { // 若连接到主机成功isGameConnected = true; isOnChess = true; isCreator = true; userControlPad.createButton.setEnabled(false); userControlPad.joinButton.setEnabled(false); userControlPad.cancelButton.setEnabled(true); firPad.firThread.sendMessage("/creatgame " + "[inchess]" + chessClientName); } } else { // 若游戏端口连接中isOnChess = true; isCreator = true; userControlPad.createButton.setEnabled(false); userControlPad.joinButton.setEnabled(false); userControlPad.cancelButton.setEnabled(true); firPad.firThread.sendMessage("/creatgame " + "[inchess]" + chessClientName); } } catch (Exception ec) { isGameConnected = false; isOnChess = false; isCreator = false; userControlPad.createButton.setEnabled(true); userControlPad.joinButton.setEnabled(true); userControlPad.cancelButton.setEnabled(false); ec.printStackTrace(); userChatPad.chatTextArea.setText("不能连接: /n" + ec); } } if (e.getSource() == userControlPad.cancelButton) { // 退出游戏按钮单击事件if (isOnChess) { // 游戏中firPad.firThread.sendMessage("/giveup " + chessClientName); firPad.setVicStatus(-1 * firPad.chessColor); userControlPad.createButton.setEnabled(true); userControlPad.joinButton.setEnabled(true); userControlPad.cancelButton.setEnabled(false); firPad.statusText.setText("请创建或加入游戏!"); } if (!isOnChess) { // 非游戏中userControlPad.createButton.setEnabled(true); userControlPad.joinButton.setEnabled(true); userControlPad.cancelButton.setEnabled(false); firPad.statusText.setText("请创建或加入游戏!"); } isParticipant = isCreator = false; } } public void keyPressed(KeyEvent e) { TextField inputwords = (TextField) e.getSource(); if (e.getKeyCode() == KeyEvent.VK_ENTER) { // 处理回车按键事件if (userInputPad.userChoice.getSelectedItem().equals("所有用户")) { // 给所有人发信息try { // 发送信息outputStream.writeUTF(inputwords.getText()); inputwords.setText(""); } catch (Exception ea) { userChatPad.chatTextArea .setText("不能连接到服务器!/n"); userListPad.userList.removeAll(); userInputPad.userChoice.removeAll(); inputwords.setText(""); userControlPad.connectButton.setEnabled(true); } } else { // 给指定人发信息try { outputStream.writeUTF("/" + userInputPad.userChoice.getSelectedItem() + " " + inputwords.getText()); inputwords.setText(""); } catch (Exception ea) { userChatPad.chatTextArea .setText("不能连接到服务器!/n"); userListPad.userList.removeAll(); userInputPad.userChoice.removeAll(); inputwords.setText(""); userControlPad.connectButton.setEnabled(true); } } } } public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} public static void main(String args[]) { FIRClient chessClient = new FIRClient(); } } 2.开发客户端线程
import java.io.IOException; import java.util.StringTokenizer; import javax.swing.DefaultListModel; import javax.swing.ListModel; /** * Created by Administrator on 2016/11/21. */ public class FIRClientThread extends Thread{ public FIRClient firClient; public FIRClientThread(FIRClient firClient) { this.firClient = firClient; } public void dealWithMsg(String msgReceived) { if (msgReceived.startsWith("/userlist ")) { // 若取得的信息为用户列表StringTokenizer userToken = new StringTokenizer(msgReceived, " "); int userNumber = 0; // 清空客户端用户列表firClient.userListPad.userList.removeAll(); // 清空客户端用户下拉框firClient.userInputPad.userChoice.removeAll(); // 给客户端用户下拉框添加一个选项firClient.userInputPad.userChoice.addItem("所有用户"); while (userToken.hasMoreTokens()) { // 当收到的用户信息列表中存在数据时String user = (String) userToken.nextToken(" "); // 取得用户信息if (userNumber > 0 && !user.startsWith("[inchess]")) { // 用户信息有效时firClient.userListPad.userList.add(user);// 将用户信息添加到用户列表中firClient.userInputPad.userChoice.addItem(user); // 将用户信息添加到用户下拉框中} userNumber++; } firClient.userInputPad.userChoice.setSelectedIndex(0);// 下拉框默认选中所有人} else if (msgReceived.startsWith("/yourname ")) { // 收到的信息为用户本名时firClient.chessClientName = msgReceived.substring(10); // 取得用户本名firClient.setTitle("Java 五子棋客户端" + "用户名:" + firClient.chessClientName); // 设置程序Frame的标题} else if (msgReceived.equals("/reject")) { // 收到的信息为拒绝用户时try { firClient.firPad.statusText.setText("不能加入游戏!"); firClient.userControlPad.cancelButton.setEnabled(false); firClient.userControlPad.joinButton.setEnabled(true); firClient.userControlPad.createButton.setEnabled(true); } catch (Exception ef) { firClient.userChatPad.chatTextArea .setText("Cannot close!"); } firClient.userControlPad.joinButton.setEnabled(true); } else if (msgReceived.startsWith("/peer ")) { // 收到信息为游戏中的等待时firClient.firPad.chessPeerName = msgReceived.substring(6); if (firClient.isCreator) { // 若用户为游戏建立者firClient.firPad.chessColor = 1; // 设定其为黑棋先行firClient.firPad.isMouseEnabled = true; firClient.firPad.statusText.setText("黑方下..."); } else if (firClient.isParticipant) { // 若用户为游戏加入者firClient.firPad.chessColor = -1; // 设定其为白棋后性firClient.firPad.statusText.setText("游戏加入,等待对手."); } } else if (msgReceived.equals("/youwin")) { // 收到信息为胜利信息firClient.isOnChess = false; firClient.firPad.setVicStatus(firClient.firPad.chessColor); firClient.firPad.statusText.setText("对手退出"); firClient.firPad.isMouseEnabled = false; } else if (msgReceived.equals("/OK")) { // 收到信息为成功创建游戏firClient.firPad.statusText.setText("游戏创建等待对手"); } else if (msgReceived.equals("/error")) { // 收到信息错误firClient.userChatPad.chatTextArea.append("错误,退出程序./n"); } else { firClient.userChatPad.chatTextArea.append(msgReceived + "/n"); firClient.userChatPad.chatTextArea.setCaretPosition( firClient.userChatPad.chatTextArea.getText().length()); } } public void run() { String message = ""; try { while (true) { // 等待聊天信息,进入wait状态message = firClient.inputStream.readUTF(); dealWithMsg(message); } } catch (IOException es){} } }至此,网络版五子棋就算是开发完成了。关于这么多类和包的关系如下图:
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.