溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

Java實(shí)現(xiàn)五子棋網(wǎng)絡(luò)版的方法

發(fā)布時(shí)間:2021-04-15 14:18:38 來(lái)源:億速云 閱讀:431 作者:小新 欄目:編程語(yǔ)言

這篇文章主要介紹了Java實(shí)現(xiàn)五子棋網(wǎng)絡(luò)版的方法,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

具體內(nèi)容如下

需求分析:

對(duì)于網(wǎng)絡(luò)五子棋而言,在普通五子棋的基礎(chǔ)上需要添加以下功能:

1.擁有服務(wù)器端和客戶(hù)端,用戶(hù)通過(guò)客戶(hù)端登錄服務(wù)器后可與其他登錄的用戶(hù)進(jìn)行對(duì)弈

2.服務(wù)器支持多組用戶(hù)同時(shí)進(jìn)行對(duì)弈

3.用戶(hù)可以在服務(wù)器上創(chuàng)建新游戲或加入已創(chuàng)建的游戲

4.用戶(hù)在下棋的時(shí)候可以進(jìn)行聊天交流

由上可以知道需要實(shí)現(xiàn)的功能:

·提供服務(wù)器和客戶(hù)端的功能

·服務(wù)器將監(jiān)聽(tīng)客戶(hù)端的登錄情況并允許多個(gè)客戶(hù)端進(jìn)行登錄

·用戶(hù)通過(guò)客戶(hù)端可以登錄服務(wù)器,之后可以看到服務(wù)器當(dāng)前在線的其他用戶(hù),并與他們進(jìn)行聊天等

·用戶(hù)登錄服務(wù)器后,可以創(chuàng)建新的五子棋游戲或加入已創(chuàng)建的五子棋游戲

·用戶(hù)通過(guò)客戶(hù)端可以像普通五子棋那樣與其他用戶(hù)對(duì)弈

根據(jù)功能將網(wǎng)絡(luò)五子棋分為4個(gè)模塊:即用戶(hù)面板模塊、棋盤(pán)面板模塊、五子棋服務(wù)器模塊、五子棋客戶(hù)端模塊

Java實(shí)現(xiàn)五子棋網(wǎng)絡(luò)版的方法

下面我們開(kāi)始進(jìn)行編譯用戶(hù)面板模塊:

1.開(kāi)發(fā)用戶(hù)列表面板

import java.awt.*; 
 
/** 
 * Created by Administrator on 2016/11/21. 
 */ 
//初始狀態(tài)下將添加10個(gè)名稱(chēng)為“無(wú)用戶(hù)“的信息到列表中,說(shuō)明服務(wù)器最多支持10個(gè)用戶(hù)同時(shí)在線 
//該列表被添加到面板中,使用“BorderLayout”布局格式 
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+"."+"無(wú)用戶(hù)"); 
 } 
 add(userList,BorderLayout.CENTER); 
 } 
}

2.開(kāi)發(fā)用戶(hù)聊天面板

import javax.swing.*; 
import java.awt.*; 
 
/** 
 * Created by Administrator on 2016/11/21. 
 */ 
//聊天面板為一個(gè)TextArea視圖控件,擁有一個(gè)垂直方向的滾動(dòng)條。 
//該TextArea被添加到面板中,使用“BorderLayout”布局格式。 
public class UserChatPad extends JPanel{ 
 public JTextArea chatTextArea=new JTextArea("命令區(qū)域",18,20); 
 public UserChatPad(){ 
 setLayout(new BorderLayout()); 
 chatTextArea.setAutoscrolls(true); 
 chatTextArea.setLineWrap(true); 
 add(chatTextArea,BorderLayout.CENTER); 
 } 
}

3.開(kāi)發(fā)用戶(hù)輸入面板

import javax.swing.*; 
import java.awt.*; 
 
/** 
 * Created by Administrator on 2016/11/21. 
 */ 
//面板包含兩個(gè)視圖控件 
//contentInpitted為T(mén)extField控件,用戶(hù)可以在其中輸入聊天信息 
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+"."+"無(wú)用戶(hù)"); 
 } 
 userChoice.setSize(60,24); 
 add(userChoice); 
 add(contentInputted); 
 } 
}

4.開(kāi)發(fā)用戶(hù)操作面板

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("連接到服務(wù)器"); 
 public JButton createButton = new JButton("創(chuàng)建游戲"); 
 public JButton joinButton = new JButton("加入游戲"); 
 public JButton cancelButton = new JButton("放棄游戲"); 
 public JButton exitButton = new JButton("退出游戲"); 
 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); 
 } 
}

下面開(kāi)始開(kāi)發(fā)棋盤(pán)面板模塊

1.開(kāi)發(fā)黑棋類(lèi)

import java.awt.*; 
 
/** 
 * Created by Administrator on 2016/11/21. 
 */ 
public class FIRPointBlack extends Canvas { 
 FIRPad padBelonged; // 黑棋所屬的棋盤(pán) 
 
 public FIRPointBlack(FIRPad padBelonged) 
 { 
 setSize(20, 20); // 設(shè)置棋子大小 
 this.padBelonged = padBelonged; 
 } 
 
 public void paint(Graphics g) 
 { // 畫(huà)棋子 
 g.setColor(Color.black); 
 g.fillOval(0, 0, 14, 14); 
 } 
}

2.開(kāi)發(fā)白棋類(lèi)

import java.awt.*; 
 
/** 
 * Created by Administrator on 2016/11/21. 
 */ 
public class FIRPointWhite extends Canvas{ 
 FIRPad padBelonged; // 白棋所屬的棋盤(pán) 
 
 public FIRPointWhite(FIRPad padBelonged) 
 { 
 setSize(20, 20); 
 this.padBelonged = padBelonged; 
 } 
 
 public void paint(Graphics g) 
 { // 畫(huà)棋子 
 g.setColor(Color.white); 
 g.fillOval(0, 0, 14, 14); 
 } 
}

3.開(kāi)發(fā)棋盤(pán)面板

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{ 
 // 鼠標(biāo)是否能使用 
 public boolean isMouseEnabled = false; 
 // 是否勝利 
 public boolean isWinned = false; 
 // 是否在下棋中 
 public boolean isGaming = false; 
 // 棋子的x軸坐標(biāo)位 
 public int chessX_POS = -1; 
 // 棋子的y軸坐標(biāo)位 
 public int chessY_POS = -1; 
 // 棋子的顏色 
 public int chessColor = 1; 
 // 黑棋x軸坐標(biāo)位數(shù)組 
 public int chessBlack_XPOS[] = new int[200]; 
 // 黑棋y軸坐標(biāo)位數(shù)組 
 public int chessBlack_YPOS[] = new int[200]; 
 // 白棋x軸坐標(biāo)位數(shù)組 
 public int chessWhite_XPOS[] = new int[200]; 
 // 白棋y軸坐標(biāo)位數(shù)組 
 public int chessWhite_YPOS[] = new int[200]; 
 // 黑棋數(shù)量 
 public int chessBlackCount = 0; 
 // 白棋數(shù)量 
 public int chessWhiteCount = 0; 
 // 黑棋獲勝次數(shù) 
 public int chessBlackVicTimes = 0; 
 // 白棋獲勝次數(shù) 
 public int chessWhiteVicTimes = 0; 
 // 套接口 
 public Socket chessSocket; 
 public DataInputStream inputData; 
 public DataOutputStream outputData; 
 public String chessSelfName = null; 
 public String chessPeerName = null; 
 public String host = null; 
 public int port = 4331; 
 public TextField statusText = new TextField("請(qǐng)連接服務(wù)器!"); 
 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); 
 } 
 
 // 連接到主機(jī) 
 public boolean connectServer(String ServerIP, int ServerPort) throws Exception 
 { 
 try 
 { 
  // 取得主機(jī)端口 
  chessSocket = new Socket(ServerIP, ServerPort); 
  // 取得輸入流 
  inputData = new DataInputStream(chessSocket.getInputStream()); 
  // 取得輸出流 
  outputData = new DataOutputStream(chessSocket.getOutputStream()); 
  firThread.start(); 
  return true; 
 } 
 catch (IOException ex) 
 { 
  statusText.setText("連接失敗! \n"); 
 } 
 return false; 
 } 
 
 // 設(shè)定勝利時(shí)的棋盤(pán)狀態(tài) 
 public void setVicStatus(int vicChessColor) 
 { 
 // 清空棋盤(pán) 
 this.removeAll(); 
 // 將黑棋的位置設(shè)置到零點(diǎn) 
 for (int i = 0; i <= chessBlackCount; i++) 
 { 
  chessBlack_XPOS[i] = 0; 
  chessBlack_YPOS[i] = 0; 
 } 
 // 將白棋的位置設(shè)置到零點(diǎn) 
 for (int i = 0; i <= chessWhiteCount; i++) 
 { 
  chessWhite_XPOS[i] = 0; 
  chessWhite_YPOS[i] = 0; 
 } 
 // 清空棋盤(pán)上的黑棋數(shù) 
 chessBlackCount = 0; 
 // 清空棋盤(pán)上的白棋數(shù) 
 chessWhiteCount = 0; 
 add(statusText); 
 statusText.setBounds(40, 5, 360, 24); 
 if (vicChessColor == 1) 
 { // 黑棋勝 
  chessBlackVicTimes++; 
  statusText.setText("黑方勝,黑:白 " + chessBlackVicTimes + ":" + chessWhiteVicTimes 
   + ",游戲重啟,等待白方..."); 
 } 
 else if (vicChessColor == -1) 
 { // 白棋勝 
  chessWhiteVicTimes++; 
  statusText.setText("白方勝,黑:白 " + chessBlackVicTimes + ":" + chessWhiteVicTimes 
   + ",游戲重啟,等待黑方..."); 
 } 
 } 
 
 // 取得指定棋子的位置 
 public void setLocation(int xPos, int yPos, int chessColor) 
 { 
 if (chessColor == 1) 
 { // 棋子為黑棋時(shí) 
  chessBlack_XPOS[chessBlackCount] = xPos * 20; 
  chessBlack_YPOS[chessBlackCount] = yPos * 20; 
  chessBlackCount++; 
 } 
 else if (chessColor == -1) 
 { // 棋子為白棋時(shí) 
  chessWhite_XPOS[chessWhiteCount] = xPos * 20; 
  chessWhite_YPOS[chessWhiteCount] = yPos * 20; 
  chessWhiteCount++; 
 } 
 } 
 
 // 判斷當(dāng)前狀態(tài)是否為勝利狀態(tài) 
 public boolean checkVicStatus(int xPos, int yPos, int chessColor) 
 { 
 int chessLinkedCount = 1; // 連接棋子數(shù) 
 int chessLinkedCompare = 1; // 用于比較是否要繼續(xù)遍歷一個(gè)棋子的相鄰網(wǎng)格 
 int chessToCompareIndex = 0; // 要比較的棋子在數(shù)組中的索引位置 
 int closeGrid = 1; // 相鄰網(wǎng)格的位置 
 if (chessColor == 1) 
 { // 黑棋時(shí) 
  chessLinkedCount = 1; // 將該棋子自身算入的話,初始連接數(shù)為1 
  //以下每對(duì)for循環(huán)語(yǔ)句為一組,因?yàn)橄缕诘奈恢媚芪挥谥虚g而非兩端 
  for (closeGrid = 1; closeGrid <= 4; closeGrid++) 
  { // 遍歷相鄰4個(gè)網(wǎng)格 
  for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) 
  { // 遍歷棋盤(pán)上所有黑棋子 
   if (((xPos + closeGrid) * 20 == chessBlack_XPOS[chessToCompareIndex]) 
    && ((yPos * 20) == chessBlack_YPOS[chessToCompareIndex])) 
   { // 判斷當(dāng)前下的棋子的右邊4個(gè)棋子是否都為黑棋 
   chessLinkedCount = chessLinkedCount + 1; // 連接數(shù)加1 
   if (chessLinkedCount == 5) 
   { // 五子相連時(shí),勝利 
    return true; 
   } 
   } 
  } 
  if (chessLinkedCount == (chessLinkedCompare + 1)) { 
   chessLinkedCompare++; 
  } 
  else {// 若中間有一個(gè)棋子非黑棋,則會(huì)進(jìn)入此分支,此時(shí)無(wú)需再遍歷 
   break; 
  } 
  } 
  for (closeGrid = 1; closeGrid <= 4; closeGrid++) 
  { 
  for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) 
  { 
   if (((xPos - closeGrid) * 20 == chessBlack_XPOS[chessToCompareIndex]) 
    && (yPos * 20 == chessBlack_YPOS[chessToCompareIndex])) 
   { // 判斷當(dāng)前下的棋子的左邊4個(gè)棋子是否都為黑棋 
   chessLinkedCount++; 
   if (chessLinkedCount == 5) 
   { 
    return true; 
   } 
   } 
  } 
  if (chessLinkedCount == (chessLinkedCompare + 1)) { 
   chessLinkedCompare++; 
  } 
  else { 
   break; 
  } 
  } 
  // 進(jìn)入新的一組for循環(huán)時(shí)要將連接數(shù)等重置 
  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])) 
   { // 判斷當(dāng)前下的棋子的上邊4個(gè)棋子是否都為黑棋 
   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])) 
   { // 判斷當(dāng)前下的棋子的下邊4個(gè)棋子是否都為黑棋 
   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])) 
   { // 判斷當(dāng)前下的棋子的左上方向4個(gè)棋子是否都為黑棋 
   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])) 
   { // 判斷當(dāng)前下的棋子的右下方向4個(gè)棋子是否都為黑棋 
   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])) 
   { // 判斷當(dāng)前下的棋子的右上方向4個(gè)棋子是否都為黑棋 
   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])) 
   { // 判斷當(dāng)前下的棋子的左下方向4個(gè)棋子是否都為黑棋 
   chessLinkedCount++; 
   if (chessLinkedCount == 5) 
   { 
    return true; 
   } 
   } 
  } 
  if (chessLinkedCount == (chessLinkedCompare + 1)) { 
   chessLinkedCompare++; 
  } 
  else { 
   break; 
  } 
  } 
 } 
 else if (chessColor == -1) 
 { // 白棋時(shí) 
  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])) 
   {// 判斷當(dāng)前下的棋子的右邊4個(gè)棋子是否都為白棋 
   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])) 
   {// 判斷當(dāng)前下的棋子的左邊4個(gè)棋子是否都為白棋 
   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])) 
   {// 判斷當(dāng)前下的棋子的上邊4個(gè)棋子是否都為白棋 
   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])) 
   {// 判斷當(dāng)前下的棋子的下邊4個(gè)棋子是否都為白棋 
   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])) 
   {// 判斷當(dāng)前下的棋子的左上方向4個(gè)棋子是否都為白棋 
   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])) 
   {// 判斷當(dāng)前下的棋子的右下方向4個(gè)棋子是否都為白棋 
   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])) 
   {// 判斷當(dāng)前下的棋子的右上方向4個(gè)棋子是否都為白棋 
   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])) 
   {// 判斷當(dāng)前下的棋子的左下方向4個(gè)棋子是否都為白棋 
   chessLinkedCount++; 
   if (chessLinkedCount == 5) 
   { 
    return (true); 
   } 
   } 
  } 
  if (chessLinkedCount == (chessLinkedCompare + 1)) { 
   chessLinkedCompare++; 
  } 
  else { 
   break; 
  } 
  } 
 } 
 return false; 
 } 
 
 // 畫(huà)棋盤(pán) 
 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(217, 217, 6, 6); 
 } 
 
 // 畫(huà)棋子 
 public void paintFirPoint(int xPos, int yPos, int chessColor) 
 { 
 FIRPointBlack firPBlack = new FIRPointBlack(this); 
 FIRPointWhite firPWhite = new FIRPointWhite(this); 
 if (chessColor == 1 && isMouseEnabled) 
 { // 黑棋 
  // 設(shè)置棋子的位置 
  setLocation(xPos, yPos, chessColor); 
  // 取得當(dāng)前局面狀態(tài) 
  isWinned = checkVicStatus(xPos, yPos, chessColor); 
  if (isWinned == false) 
  { // 非勝利狀態(tài) 
  firThread.sendMessage("/" + chessPeerName + " /chess " 
   + xPos + " " + yPos + " " + chessColor); 
  this.add(firPBlack); // 將棋子添加到棋盤(pán)中 
  firPBlack.setBounds(xPos * 20 - 7, 
   yPos * 20 - 7, 16, 16); // 設(shè)置棋子邊界 
  statusText.setText("黑(第" + chessBlackCount + "步)" 
   + xPos + " " + yPos + ",輪到白方."); 
  isMouseEnabled = false; // 將鼠標(biāo)設(shè)為不可用 
  } 
  else 
  { // 勝利狀態(tài) 
  firThread.sendMessage("/" + chessPeerName + " /chess " 
   + xPos + " " + yPos + " " + chessColor); 
  this.add(firPBlack); 
  firPBlack.setBounds(xPos * 20 - 7, 
   yPos * 20 - 7, 16, 16); 
  setVicStatus(1); // 調(diào)用勝利方法,傳入?yún)?shù)為黑棋勝利 
  isMouseEnabled = false; 
  } 
 } 
 else if (chessColor == -1 && isMouseEnabled) 
 { // 白棋 
  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("白(第" + chessWhiteCount + "步)" 
   + xPos + " " + yPos + ",輪到黑方."); 
  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); // 調(diào)用勝利方法,傳入?yún)?shù)為白棋 
  isMouseEnabled = false; 
  } 
 } 
 } 
 
 // 畫(huà)網(wǎng)絡(luò)棋盤(pán) 
 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("黑(第" + chessBlackCount + "步)" 
   + xPos + " " + yPos + ",輪到白方."); 
  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("白(第" + chessWhiteCount + "步)" 
   + xPos + " " + yPos + ",輪到黑方."); 
  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; 
  } 
 } 
 } 
 
 // 捕獲下棋事件 
 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) 
  { 
  // 下棋位置不正確時(shí),不執(zhí)行任何操作 
  } 
  else 
  { 
  paintFirPoint(a, b, chessColor); // 畫(huà)棋子 
  } 
 } 
 } 
 
 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.開(kāi)發(fā)棋盤(pán)線程

import java.util.StringTokenizer; 
import java.io.IOException; 
 
/** 
 * Created by Administrator on 2016/11/21. 
 */ 
public class FIRThread extends Thread{ 
 FIRPad currPad; // 當(dāng)前線程的棋盤(pán) 
 
 public FIRThread(FIRPad currPad) 
 { 
 this.currPad = currPad; 
 } 
 
 // 處理取得的信息 
 public void dealWithMsg(String msgReceived) 
 { 
 if (msgReceived.startsWith("/chess ")) 
 { // 收到的信息為下棋 
  StringTokenizer userMsgToken = new StringTokenizer(msgReceived, " "); 
  // 表示棋子信息的數(shù)組、0索引為:x坐標(biāo);1索引位:y坐標(biāo);2索引位:棋子顏色 
  String[] chessInfo = { "-1", "-1", "0" }; 
  int i = 0; // 標(biāo)志位 
  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 ")) 
 { // 收到的信息為改名 
  currPad.chessSelfName = msgReceived.substring(10); 
 } 
 else if (msgReceived.equals("/error")) 
 { // 收到的為錯(cuò)誤信息 
  currPad.statusText.setText("用戶(hù)不存在,請(qǐng)重新加入!"); 
 } 
 } 
 
 // 發(fā)送信息 
 public void sendMessage(String sndMessage) 
 { 
 try 
 { 
  currPad.outputData.writeUTF(sndMessage); 
 } 
 catch (Exception ea) 
 { 
  ea.printStackTrace();; 
 } 
 } 
 
 public void run() 
 { 
 String msgReceived = ""; 
 try 
 { 
  while (true) 
  { // 等待信息輸入 
  msgReceived = currPad.inputData.readUTF(); 
  dealWithMsg(msgReceived); 
  } 
 } 
 catch (IOException es){} 
 } 
}

下面開(kāi)始開(kāi)發(fā)服務(wù)器模塊

1.開(kāi)發(fā)服務(wù)器信息面板

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("當(dāng)前連接數(shù):", 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.開(kāi)發(fā)服務(wù)器進(jìn)程

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; // 保存客戶(hù)端套接口信息 
 Hashtable clientDataHash; // 保存客戶(hù)端端口與輸出流對(duì)應(yīng)的Hash 
 Hashtable clientNameHash; // 保存客戶(hù)端套接口和客戶(hù)名對(duì)應(yīng)的Hash 
 Hashtable chessPeerHash; // 保存游戲創(chuàng)建者和游戲加入者對(duì)應(yīng)的Hash 
 ServerMsgPanel serverMsgPanel; 
 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")) 
  { // 收到的信息為更新用戶(hù)列表 
  Feedback(getUserList()); 
  } 
  else if (msgReceived.startsWith("/creatgame [inchess]")) 
  { // 收到的信息為創(chuàng)建游戲 
  String gameCreaterName = msgReceived.substring(20); //取得服務(wù)器名 
  synchronized (clientNameHash) 
  { // 將用戶(hù)端口放到用戶(hù)列表中 
   clientNameHash.put(clientSocket, msgReceived.substring(11)); 
  } 
  synchronized (chessPeerHash) 
  { // 將主機(jī)設(shè)置為等待狀態(tài) 
   chessPeerHash.put(gameCreaterName, "wait"); 
  } 
  Feedback("/yourname " + clientNameHash.get(clientSocket)); 
  sendGamePeerMsg(gameCreaterName, "/OK"); 
  sendPublicMsg(getUserList()); 
  } 
  else if (msgReceived.startsWith("/joingame ")) 
  { // 收到的信息為加入游戲時(shí) 
  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; // 取得游戲者命 
   } 
   nameIndex++; 
  } 
  gameCreatorName = playerNames[0]; 
  gamePaticipantName = playerNames[1]; 
  if (chessPeerHash.containsKey(gameCreatorName) 
   && chessPeerHash.get(gameCreatorName).equals("wait")) 
  { // 游戲已創(chuàng)建 
   synchronized (clientNameHash) 
   { // 增加游戲加入者的套接口與名稱(chēng)的對(duì)應(yīng) 
   clientNameHash.put(clientSocket, 
    ("[inchess]" + gamePaticipantName)); 
   } 
   synchronized (chessPeerHash) 
   { // 增加或修改游戲創(chuàng)建者與游戲加入者的名稱(chēng)的對(duì)應(yīng) 
   chessPeerHash.put(gameCreatorName, gamePaticipantName); 
   } 
   sendPublicMsg(getUserList()); 
   // 發(fā)送信息給游戲加入者 
   sendGamePeerMsg(gamePaticipantName, 
    ("/peer " + "[inchess]" + gameCreatorName)); 
   // 發(fā)送游戲給游戲創(chuàng)建者 
   sendGamePeerMsg(gameCreatorName, 
    ("/peer " + "[inchess]" + gamePaticipantName)); 
  } 
  else 
  { // 若游戲未創(chuàng)建則拒絕加入游戲 
   sendGamePeerMsg(gamePaticipantName, "/reject"); 
   try 
   { 
   closeClient(); 
   } 
   catch (Exception ez) 
   { 
   ez.printStackTrace(); 
   } 
  } 
  } 
  else if (msgReceived.startsWith("/[inchess]")) 
  { // 收到的信息為游戲中時(shí) 
  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 ")) 
  { // 收到的信息為放棄游戲時(shí) 
  String chessClientName = msgReceived.substring(8); 
  if (chessPeerHash.containsKey(chessClientName) 
   && !((String) chessPeerHash.get(chessClientName)) 
   .equals("wait")) 
  { // 勝利方為游戲加入者,發(fā)送勝利信息 
   sendGamePeerMsg((String) chessPeerHash.get(chessClientName), 
    "/youwin"); 
   synchronized (chessPeerHash) 
   { // 刪除退出游戲的用戶(hù) 
   chessPeerHash.remove(chessClientName); 
   } 
  } 
  if (chessPeerHash.containsValue(chessClientName)) 
  { // 勝利方為游戲創(chuàng)建者,發(fā)送勝利信息 
   sendGamePeerMsg((String) getHashKey(chessPeerHash, 
    chessClientName), "/youwin"); 
   synchronized (chessPeerHash) 
   {// 刪除退出游戲的用戶(hù) 
   chessPeerHash.remove((String) getHashKey(chessPeerHash, 
    chessClientName)); 
   } 
  } 
  } 
  else 
  { // 收到的信息為其它信息時(shí) 
  int lastLocation = msgReceived.indexOf(" ", 0); 
  if (lastLocation == -1) 
  { 
   Feedback("無(wú)效命令"); 
   return; 
  } 
  } 
 } 
 else 
 { 
  msgReceived = clientNameHash.get(clientSocket) + ">" + msgReceived; 
  serverMsgPanel.msgTextArea.append(msgReceived + "\n"); 
  sendPublicMsg(msgReceived); 
  serverMsgPanel.msgTextArea.setCaretPosition(serverMsgPanel.msgTextArea.getText() 
   .length()); 
 } 
 } 
 
 // 發(fā)送公開(kāi)信息 
 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(); 
  } 
  } 
 } 
 } 
 
 // 發(fā)送信息給指定的游戲中的用戶(hù) 
 public boolean sendGamePeerMsg(String gamePeerTarget, String gamePeerMsg) 
 { 
 for (Enumeration enu = clientDataHash.keys(); enu.hasMoreElements();) 
 { // 遍歷以取得游戲中的用戶(hù)的套接口 
  Socket userClient = (Socket) enu.nextElement(); 
  if (gamePeerTarget.equals((String) clientNameHash.get(userClient)) 
   && !gamePeerTarget.equals((String) clientNameHash 
   .get(clientSocket))) 
  { // 找到要發(fā)送信息的用戶(hù)時(shí) 
  synchronized (clientDataHash) 
  { 
   // 建立輸出流 
   DataOutputStream peerOutData = (DataOutputStream) clientDataHash 
    .get(userClient); 
   try 
   { 
   // 發(fā)送信息 
   peerOutData.writeUTF(gamePeerMsg); 
   } 
   catch (IOException es) 
   { 
   es.printStackTrace(); 
   } 
  } 
  return false; 
  } 
 } 
 return true; 
 } 
 
 // 發(fā)送反饋信息給連接到主機(jī)的人 
 public void Feedback(String feedBackMsg) 
 { 
 synchronized (clientDataHash) 
 { 
  DataOutputStream outputData = (DataOutputStream) clientDataHash 
   .get(clientSocket); 
  try 
  { 
  outputData.writeUTF(feedBackMsg); 
  } 
  catch (Exception eb) 
  { 
  eb.printStackTrace(); 
  } 
 } 
 } 
 
 // 取得用戶(hù)列表 
 public String getUserList() 
 { 
 String userList = "/userlist"; 
 for (Enumeration enu = clientNameHash.elements(); enu.hasMoreElements();) 
 { 
  userList = userList + " " + (String) enu.nextElement(); 
 } 
 return userList; 
 } 
 
 // 根據(jù)value值從Hashtable中取得相應(yīng)的key 
 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; 
 } 
 
 // 剛連接到主機(jī)時(shí)執(zhí)行的方法 
 public void sendInitMsg() 
 { 
 sendPublicMsg(getUserList()); 
 Feedback("/yourname " + (String) clientNameHash.get(clientSocket)); 
 Feedback("Java 五子棋客戶(hù)端"); 
 Feedback("/list --更新用戶(hù)列表"); 
 Feedback("/<username> <talk> --私聊"); 
 Feedback("注意:命令必須對(duì)所有用戶(hù)發(fā)送"); 
 } 
 
 public void closeClient() 
 { 
 serverMsgPanel.msgTextArea.append("用戶(hù)斷開(kāi)連接:" + clientSocket + "\n"); 
 synchronized (chessPeerHash) 
 { //如果是游戲客戶(hù)端主機(jī) 
  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) 
 { // 刪除客戶(hù)數(shù)據(jù) 
  clientDataHash.remove(clientSocket); 
 } 
 synchronized (clientNameHash) 
 { // 刪除客戶(hù)數(shù)據(jù) 
  clientNameHash.remove(clientSocket); 
 } 
 sendPublicMsg(getUserList()); 
 serverMsgPanel.statusLabel.setText("當(dāng)前連接數(shù):" + clientDataHash.size()); 
 try 
 { 
  clientSocket.close(); 
 } 
 catch (IOException exx) 
 { 
  exx.printStackTrace(); 
 } 
 isClientClosed = true; 
 } 
 
 public void run() 
 { 
 DataInputStream inputData; 
 synchronized (clientDataHash) 
 { 
  serverMsgPanel.statusLabel.setText("當(dāng)前連接數(shù):" + clientDataHash.size()); 
 } 
 try 
 { // 等待連接到主機(jī)的信息 
  inputData = new DataInputStream(clientSocket.getInputStream()); 
  sendInitMsg(); 
  while (true) 
  { 
  String message = inputData.readUTF(); 
  dealWithMsg(message); 
  } 
 } 
 catch (IOException esx){} 
 finally 
 { 
  if (!isClientClosed) 
  { 
  closeClient(); 
  } 
 } 
 } 
}

3.開(kāi)發(fā)服務(wù)器端

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("服務(wù)器狀態(tài)"); 
 JButton closeServerButton = new JButton("關(guān)閉服務(wù)器"); 
 Panel buttonPanel = new Panel(); 
 ServerMsgPanel serverMsgPanel = new ServerMsgPanel(); 
 ServerSocket serverSocket; 
 Hashtable clientDataHash = new Hashtable(50); //將客戶(hù)端套接口和輸出流綁定 
 Hashtable clientNameHash = new Hashtable(50); //將客戶(hù)端套接口和客戶(hù)名綁定 
 Hashtable chessPeerHash = new Hashtable(50); //將游戲創(chuàng)建者和游戲加入者綁定 
 
 public FIRServer() 
 { 
 super("Java 五子棋服務(wù)器"); 
 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(); 
 } 
 } 
 
 // 用指定端口和面板創(chuàng)建服務(wù)器 
 public void createServer(int port, ServerMsgPanel serverMsgPanel) throws IOException 
 { 
 Socket clientSocket; // 客戶(hù)端套接口 
 long clientAccessNumber = 1; // 連接到主機(jī)的客戶(hù)數(shù)量 
 this.serverMsgPanel = serverMsgPanel; // 設(shè)定當(dāng)前主機(jī) 
 try 
 { 
  serverSocket = new ServerSocket(port); 
  serverMsgPanel.msgTextArea.setText("服務(wù)器啟動(dòng)于:" 
   + InetAddress.getLocalHost() + ":" //djr 
   + serverSocket.getLocalPort() + "\n"); 
  while (true) 
  { 
  // 監(jiān)聽(tīng)客戶(hù)端套接口的信息 
  clientSocket = serverSocket.accept(); 
  serverMsgPanel.msgTextArea.append("已連接用戶(hù):" + clientSocket + "\n"); 
  // 建立客戶(hù)端輸出流 
  DataOutputStream outputData = new DataOutputStream(clientSocket 
   .getOutputStream()); 
  // 將客戶(hù)端套接口和輸出流綁定 
  clientDataHash.put(clientSocket, outputData); 
  // 將客戶(hù)端套接口和客戶(hù)名綁定 
  clientNameHash 
   .put(clientSocket, ("新玩家" + clientAccessNumber++)); 
  // 創(chuàng)建并運(yùn)行服務(wù)器端線程 
  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) 
 { // 清空服務(wù)器信息 
  serverMsgPanel.msgTextArea.setText(""); 
 } 
 if (e.getSource() == serverStatusButton) 
 { // 顯示服務(wù)器信息 
  try 
  { 
  serverMsgPanel.msgTextArea.append("服務(wù)器信息:" 
   + InetAddress.getLocalHost() + ":" 
   + serverSocket.getLocalPort() + "\n"); 
  } 
  catch (Exception ee) 
  { 
  ee.printStackTrace(); 
  } 
 } 
 if (e.getSource() == closeServerButton) 
 { // 關(guān)閉服務(wù)器 
  System.exit(0); 
 } 
 } 
 
 public static void main(String args[]) 
 { 
 FIRServer firServer = new FIRServer(); 
 } 
}

下面開(kāi)始編寫(xiě)客戶(hù)端模塊

1.開(kāi)發(fā)客戶(hù)端

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 { 
 // 客戶(hù)端套接口 
 Socket clientSocket; 
 // 數(shù)據(jù)輸入流 
 DataInputStream inputStream; 
 // 數(shù)據(jù)輸出流 
 DataOutputStream outputStream; 
 // 用戶(hù)名 
 String chessClientName = null; 
 // 主機(jī)地址 
 String host = null; 
 // 主機(jī)端口 
 int port = 4331; 
 // 是否在聊天 
 boolean isOnChat = false; 
 // 是否在下棋 
 boolean isOnChess = false; 
 // 游戲是否進(jìn)行中 
 boolean isGameConnected = false; 
 // 是否為游戲創(chuàng)建者 
 boolean isCreator = false; 
 // 是否為游戲加入者 
 boolean isParticipant = false; 
 // 用戶(hù)列表區(qū) 
 UserListPad userListPad = new UserListPad(); 
 // 用戶(hù)聊天區(qū) 
 UserChatPad userChatPad = new UserChatPad(); 
 // 用戶(hù)操作區(qū) 
 UserControlPad userControlPad = new UserControlPad(); 
 // 用戶(hù)輸入?yún)^(qū) 
 UserInputPad userInputPad = new UserInputPad(); 
 // 下棋區(qū) 
 FIRPad firPad = new FIRPad(); 
 // 面板區(qū) 
 Panel southPanel = new Panel(); 
 Panel northPanel = new Panel(); 
 Panel centerPanel = new Panel(); 
 Panel eastPanel = new Panel(); 
 
 // 構(gòu)造方法,創(chuàng)建界面 
 public FIRClient() 
 { 
 super("Java 五子棋客戶(hù)端"); 
 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 
   { // 關(guān)閉客戶(hù)端套接口 
   clientSocket.close(); 
   } 
   catch (Exception ed){} 
  } 
  if (isOnChess || isGameConnected) 
  { // 下棋中 
   try 
   { // 關(guān)閉下棋端口 
   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地址和端口連接到服務(wù)器 
 public boolean connectToServer(String serverIP, int serverPort) throws Exception 
 { 
 try 
 { 
  // 創(chuàng)建客戶(hù)端套接口 
  clientSocket = new Socket(serverIP, serverPort); 
  // 創(chuàng)建輸入流 
  inputStream = new DataInputStream(clientSocket.getInputStream()); 
  // 創(chuàng)建輸出流 
  outputStream = new DataOutputStream(clientSocket.getOutputStream()); 
  // 創(chuàng)建客戶(hù)端線程 
  FIRClientThread clientthread = new FIRClientThread(this); 
  // 啟動(dòng)線程,等待聊天信息 
  clientthread.start(); 
  isOnChat = true; 
  return true; 
 } 
 catch (IOException ex) 
 { 
  userChatPad.chatTextArea 
   .setText("不能連接!\n"); 
 } 
 return false; 
 } 
 
 // 客戶(hù)端事件處理 
 public void actionPerformed(ActionEvent e) 
 { 
 if (e.getSource() == userControlPad.connectButton) 
 { // 連接到主機(jī)按鈕單擊事件 
  host = firPad.host = userControlPad.ipInputted.getText(); // 取得主機(jī)地址 
  try 
  { 
  if (connectToServer(host, port)) 
  { // 成功連接到主機(jī)時(shí),設(shè)置客戶(hù)端相應(yīng)的界面狀態(tài) 
   userChatPad.chatTextArea.setText(""); 
   userControlPad.connectButton.setEnabled(false); 
   userControlPad.createButton.setEnabled(true); 
   userControlPad.joinButton.setEnabled(true); 
   firPad.statusText.setText("連接成功,請(qǐng)等待!"); 
  } 
  } 
  catch (Exception ei) 
  { 
  userChatPad.chatTextArea 
   .setText("不能連接!\n"); 
  } 
 } 
 if (e.getSource() == userControlPad.exitButton) 
 { // 離開(kāi)游戲按鈕單擊事件 
  if (isOnChat) 
  { // 若用戶(hù)處于聊天狀態(tài)中 
  try 
  { // 關(guān)閉客戶(hù)端套接口 
   clientSocket.close(); 
  } 
  catch (Exception ed){} 
  } 
  if (isOnChess || isGameConnected) 
  { // 若用戶(hù)處于游戲狀態(tài)中 
  try 
  { // 關(guān)閉游戲端口 
   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)) 
  { // 若未選中要加入的用戶(hù),或選中的用戶(hù)已經(jīng)在游戲,則給出提示信息 
  firPad.statusText.setText("必須選擇一個(gè)用戶(hù)!"); 
  } 
  else 
  { // 執(zhí)行加入游戲的操作 
  try 
  { 
   if (!isGameConnected) 
   { // 若游戲套接口未連接 
   if (firPad.connectServer(firPad.host, firPad.port)) 
   { // 若連接到主機(jī)成功 
    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) 
 { // 創(chuàng)建游戲按鈕單擊事件 
  try 
  { 
  if (!isGameConnected) 
  { // 若游戲端口未連接 
   if (firPad.connectServer(firPad.host, firPad.port)) 
   { // 若連接到主機(jī)成功 
   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("請(qǐng)創(chuàng)建或加入游戲!"); 
  } 
  if (!isOnChess) 
  { // 非游戲中 
  userControlPad.createButton.setEnabled(true); 
  userControlPad.joinButton.setEnabled(true); 
  userControlPad.cancelButton.setEnabled(false); 
  firPad.statusText.setText("請(qǐng)創(chuàng)建或加入游戲!"); 
  } 
  isParticipant = isCreator = false; 
 } 
 } 
 
 public void keyPressed(KeyEvent e) 
 { 
 TextField inputwords = (TextField) e.getSource(); 
 if (e.getKeyCode() == KeyEvent.VK_ENTER) 
 { // 處理回車(chē)按鍵事件 
  if (userInputPad.userChoice.getSelectedItem().equals("所有用戶(hù)")) 
  { // 給所有人發(fā)信息 
  try 
  { 
   // 發(fā)送信息 
   outputStream.writeUTF(inputwords.getText()); 
   inputwords.setText(""); 
  } 
  catch (Exception ea) 
  { 
   userChatPad.chatTextArea 
    .setText("不能連接到服務(wù)器!\n"); 
   userListPad.userList.removeAll(); 
   userInputPad.userChoice.removeAll(); 
   inputwords.setText(""); 
   userControlPad.connectButton.setEnabled(true); 
  } 
  } 
  else 
  { // 給指定人發(fā)信息 
  try 
  { 
   outputStream.writeUTF("/" + userInputPad.userChoice.getSelectedItem() 
    + " " + inputwords.getText()); 
   inputwords.setText(""); 
  } 
  catch (Exception ea) 
  { 
   userChatPad.chatTextArea 
    .setText("不能連接到服務(wù)器!\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.開(kāi)發(fā)客戶(hù)端線程

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 ")) 
 { // 若取得的信息為用戶(hù)列表 
  StringTokenizer userToken = new StringTokenizer(msgReceived, " "); 
  int userNumber = 0; 
  // 清空客戶(hù)端用戶(hù)列表 
  firClient.userListPad.userList.removeAll(); 
  // 清空客戶(hù)端用戶(hù)下拉框 
  firClient.userInputPad.userChoice.removeAll(); 
  // 給客戶(hù)端用戶(hù)下拉框添加一個(gè)選項(xiàng) 
  firClient.userInputPad.userChoice.addItem("所有用戶(hù)"); 
  while (userToken.hasMoreTokens()) 
  { // 當(dāng)收到的用戶(hù)信息列表中存在數(shù)據(jù)時(shí) 
  String user = (String) userToken.nextToken(" "); // 取得用戶(hù)信息 
  if (userNumber > 0 && !user.startsWith("[inchess]")) 
  { // 用戶(hù)信息有效時(shí) 
   firClient.userListPad.userList.add(user);// 將用戶(hù)信息添加到用戶(hù)列表中 
   firClient.userInputPad.userChoice.addItem(user); // 將用戶(hù)信息添加到用戶(hù)下拉框中 
  } 
  userNumber++; 
  } 
  firClient.userInputPad.userChoice.setSelectedIndex(0);// 下拉框默認(rèn)選中所有人 
 } 
 else if (msgReceived.startsWith("/yourname ")) 
 { // 收到的信息為用戶(hù)本名時(shí) 
  firClient.chessClientName = msgReceived.substring(10); // 取得用戶(hù)本名 
  firClient.setTitle("Java 五子棋客戶(hù)端 " + "用戶(hù)名:" 
   + firClient.chessClientName); // 設(shè)置程序Frame的標(biāo)題 
 } 
 else if (msgReceived.equals("/reject")) 
 { // 收到的信息為拒絕用戶(hù)時(shí) 
  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 ")) 
 { // 收到信息為游戲中的等待時(shí) 
  firClient.firPad.chessPeerName = msgReceived.substring(6); 
  if (firClient.isCreator) 
  { // 若用戶(hù)為游戲建立者 
  firClient.firPad.chessColor = 1; // 設(shè)定其為黑棋先行 
  firClient.firPad.isMouseEnabled = true; 
  firClient.firPad.statusText.setText("黑方下..."); 
  } 
  else if (firClient.isParticipant) 
  { // 若用戶(hù)為游戲加入者 
  firClient.firPad.chessColor = -1; // 設(shè)定其為白棋后性 
  firClient.firPad.statusText.setText("游戲加入,等待對(duì)手."); 
  } 
 } 
 else if (msgReceived.equals("/youwin")) 
 { // 收到信息為勝利信息 
  firClient.isOnChess = false; 
  firClient.firPad.setVicStatus(firClient.firPad.chessColor); 
  firClient.firPad.statusText.setText("對(duì)手退出"); 
  firClient.firPad.isMouseEnabled = false; 
 } 
 else if (msgReceived.equals("/OK")) 
 { // 收到信息為成功創(chuàng)建游戲 
  firClient.firPad.statusText.setText("游戲創(chuàng)建等待對(duì)手"); 
 } 
 
 else if (msgReceived.equals("/error")) 
 { // 收到信息錯(cuò)誤 
  firClient.userChatPad.chatTextArea.append("錯(cuò)誤,退出程序.\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) 
  { 
  // 等待聊天信息,進(jìn)入wait狀態(tài) 
  message = firClient.inputStream.readUTF(); 
  dealWithMsg(message); 
  } 
 } 
 catch (IOException es){} 
 } 
}

至此,網(wǎng)絡(luò)版五子棋就算是開(kāi)發(fā)完成了。關(guān)于這么多類(lèi)和包的關(guān)系如下圖:

Java實(shí)現(xiàn)五子棋網(wǎng)絡(luò)版的方法

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Java實(shí)現(xiàn)五子棋網(wǎng)絡(luò)版的方法”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI