บทความนี้แบ่งปันรหัสเฉพาะสำหรับการใช้งาน Java Goziqi เวอร์ชันออนไลน์สำหรับการอ้างอิงของคุณ เนื้อหาเฉพาะมีดังนี้
การวิเคราะห์ข้อกำหนด:
สำหรับ Goji ออนไลน์ต้องมีการเพิ่มฟังก์ชั่นต่อไปนี้ตาม Goji สามัญ:
1. มีฝั่งเซิร์ฟเวอร์และไคลเอนต์ หลังจากผู้ใช้เข้าสู่ระบบเซิร์ฟเวอร์ผ่านไคลเอนต์พวกเขาสามารถเล่นเกมกับผู้ใช้ที่เข้าสู่ระบบรายอื่น
2. เซิร์ฟเวอร์รองรับผู้ใช้หลายกลุ่มในการเล่นเกมในเวลาเดียวกัน
3. ผู้ใช้สามารถสร้างเกมใหม่บนเซิร์ฟเวอร์หรือเข้าร่วมเกมที่สร้างขึ้น
4. ผู้ใช้สามารถแชทและสื่อสารในขณะที่เล่นหมากรุก
จากข้างต้นเราสามารถรู้ฟังก์ชั่นที่จำเป็นต้องใช้:
・ ให้ฟังก์ชั่นเซิร์ฟเวอร์และไคลเอนต์
・ เซิร์ฟเวอร์จะตรวจสอบสถานะการเข้าสู่ระบบของลูกค้าและอนุญาตให้ลูกค้าหลายรายเข้าสู่ระบบ
・ ผู้ใช้สามารถเข้าสู่ระบบเซิร์ฟเวอร์ผ่านไคลเอนต์แล้วพวกเขาสามารถเห็นผู้ใช้รายอื่นของเซิร์ฟเวอร์ออนไลน์ในปัจจุบันและแชทกับพวกเขา
・ หลังจากเข้าสู่เซิร์ฟเวอร์ผู้ใช้สามารถสร้างเกม Gozi ใหม่หรือเข้าร่วมเกม Gozi ที่สร้างขึ้น
・ ผู้ใช้สามารถเล่นเกมกับผู้ใช้รายอื่นเช่น Goji ธรรมดาผ่านทางไคลเอนต์
ตามฟังก์ชั่นเครือข่าย Gochi แบ่งออกเป็น 4 โมดูล: คือโมดูลแผงผู้ใช้โมดูลแผงบอร์ดโมดูล Gochi Server และโมดูลไคลเอ็นต์ Gochi
มาเริ่มรวบรวมโมดูลแผงผู้ใช้:
1. พัฒนาแผงรายการผู้ใช้
นำเข้า Java.awt.*; /*** สร้างโดยผู้ดูแลระบบเมื่อปี 2016/11/21 */// ในสถานะเริ่มต้นข้อมูล 10 รายการที่ชื่อ "ไม่มีผู้ใช้" จะถูกเพิ่มลงในรายการซึ่งระบุว่าเซิร์ฟเวอร์รองรับผู้ใช้ออนไลน์ได้มากถึง 10 คนในเวลาเดียวกัน///รายการที่เพิ่มลงในแผงควบคุมโดยใช้รูปแบบ "BorderLayout" Public UserListPad () {SetLayout (New BorderLayout ()); สำหรับ (int i = 0; i <10; i ++) {userlist.add (i+"."+"ไม่มีผู้ใช้"); } เพิ่ม (userlist, borderlayout.center); - 2. พัฒนาแผงแชทของผู้ใช้
นำเข้า Javax.swing.*; นำเข้า Java.awt.*; /*** สร้างโดยผู้ดูแลระบบเมื่อปี 2016/11/21 */// แผงแชทเป็นตัวควบคุมมุมมอง Textarea พร้อมแถบเลื่อนแนวตั้ง // textarea ถูกเพิ่มลงในแผงควบคุมโดยใช้รูปแบบการจัดวาง "BorderLayout" ชั้นเรียนสาธารณะ UserChatpad ขยาย JPanel {สาธารณะ jtextarea chattextarea = ใหม่ jtextarea ("พื้นที่บัญชาการ", 18,20); Public UserChatpad () {SetLayout (ใหม่ BorderLayout ()); chattextarea.setautoscrolls (จริง); chattextarea.setlineWrap (จริง); เพิ่ม (chattextarea, borderlayout.center); - 3. พัฒนาแผงป้อนข้อมูลผู้ใช้
นำเข้า Javax.swing.*; นำเข้า Java.awt.*; /*** สร้างโดยผู้ดูแลระบบเมื่อปี 2016/11/21 */// แผงควบคุมมีการควบคุมมุมมองสองตัว // ContentInpitted เป็นตัวควบคุม textField ซึ่งผู้ใช้สามารถป้อนข้อมูลการแชทคลาสสาธารณะ UserInputPad ขยาย JPanel {สาธารณะ Jtextfield PonitInputted = new JTextField ("", 26); สาธารณะ jcombobox userchoice = new JcomboBox (); Public UserInputPad () {SetLayout (FlowLayout ใหม่ (flowlayout.left)); สำหรับ (int i = 0; i <50; i ++) {userchoice.additem (i+"."+"ไม่มีผู้ใช้"); } userchoice.setsize (60,24); เพิ่ม (userchoice); เพิ่ม (contentInputted); - 4. พัฒนาแผงการทำงานของผู้ใช้
นำเข้า Javax.swing.*; นำเข้า Java.awt.*; /*** สร้างโดยผู้ดูแลระบบเมื่อปี 2016/11/21 */ คลาสสาธารณะ UserControlpad ขยาย JPanel {สาธารณะ jlabel iPlabel = new JLabel ("IP", jlabel.left); สาธารณะ jtextfield ipinputted = new jtextfield ("localhost", 10); สาธารณะ JButton ConnectButton = new JButton ("เชื่อมต่อกับเซิร์ฟเวอร์"); สาธารณะ JButton CreateButton = new JButton ("สร้างเกม"); สาธารณะ JButton JoinButton = New JButton ("เข้าร่วมเกม"); สาธารณะ JButton CancelButton = New JButton ("Give Up Game"); สาธารณะ JButton ExitButton = New JButton ("Exit Game"); Public UserControlpad () {setLayout (ใหม่ flowlayout (flowlayout.left)); Fetbackground (color.light_gray); เพิ่ม (iplabel); เพิ่ม (ipinputted); เพิ่ม (ConnectButton); เพิ่ม (CreateButton); เพิ่ม (JoinButton); เพิ่ม (CancelButton); เพิ่ม (ExitButton); - เริ่มพัฒนาโมดูลแผงบอร์ดด้านล่าง
1. พัฒนาหมากรุกสีดำ
นำเข้า Java.awt.*; /*** สร้างโดยผู้ดูแลระบบเมื่อปี 2016/11/21 */ คลาสสาธารณะ FirpointBlack ขยาย Canvas {Firpad Padbelonged; // บอร์ดที่หมากรุกสีดำเป็น publicbointblack (firpad padbelonged) {setsize (20, 20); // ตั้งค่าชิ้นส่วนหมากรุกขนาดนี้ padbelonged = padbelonged; } สีโมฆะสาธารณะ (กราฟิก g) {// วาดชิ้นหมากรุก G.SetColor (color.black); G.Filloval (0, 0, 14, 14); - 2. พัฒนาหมวดหมู่หมากรุกสีขาว
นำเข้า Java.awt.*; /*** สร้างโดยผู้ดูแลระบบเมื่อปี 2016/11/21 */ คลาสสาธารณะ Firpointwhite ขยาย Canvas {firpad padbelonged; // บอร์ดที่หมากรุกสีขาวเป็นสาธารณะ firpointwhite (firpad padbelonged) {setsize (20, 20); this.padbelonged = padbelonged; } สีโมฆะสาธารณะ (กราฟิก g) {// วาดชิ้นหมากรุก G.SetColor (color.white); G.Filloval (0, 0, 14, 14); - 3. พัฒนาแผงกระดานหมากรุก
นำเข้า Java.awt.*; นำเข้า java.awt.event.*; นำเข้า Java.io.*; นำเข้า Java.net.*; นำเข้า Javax.swing.jtextfield; /*** สร้างโดยผู้ดูแลระบบเมื่อปี 2016/11/21 */ คลาสสาธารณะ FIRPAD ขยายพาเนลใช้ Mouselistener, ActionListener {// สามารถใช้เมาส์ได้กับบูลีนสาธารณะ ismouseenabled = false; // ว่าจะชนะบูลีนสาธารณะ iswinned = false; // ว่าจะเล่นหมากรุกบูลีนสาธารณะ isgaming = false; // X -Axis พิกัดบิตของชิ้นหมากรุกสาธารณะ int chessx_pos = -1; // y -axis บิตบิตของชิ้นหมากรุกสาธารณะ int chessy_pos = -1; // สีของชิ้นหมากรุกสาธารณะ int chesscolor = 1; // Black X-Axis พิกัดบิตอาร์เรย์สาธารณะ int chessblack_xpos [] = new int [200]; // Black Y-Axis COUNTERBE BIT ARRAY สาธารณะ int chessBlack_ypos [] = new int [200]; // สีขาว y-axis พิกัดบิตอาร์เรย์สาธารณะ int chesswhite_xpos [] = new int [200]; // หมากรุกสีขาว y-axis พิกัดหลักอาร์เรย์สาธารณะ int chesswhite_ypos [] = new int [200]; // จำนวนหมากรุกสีดำ Public Int ChessblackCount = 0; // จำนวนหมากรุกสีขาวสาธารณะ int chesswhitecount = 0; // จำนวนหมากรุกสีดำชนะสาธารณะ int chessblackVictimes = 0; // จำนวนหมากรุกสีขาวชนะในที่สาธารณะ chesswhitevictimes = 0; // จำนวนหมากรุกสีขาวชนะในที่สาธารณะ chesswhitevictimes = 0; // ส่วนต่อประสานซ็อกเก็ตซ็อกเก็ตสาธารณะหมากรุก; Public DatainputStream InputData; Public DataOutputStream OutputData; สตริงสาธารณะ chesselfName = null; สตริงสาธารณะ ChessPeername = NULL; โฮสต์สตริงสาธารณะ = null; พอร์ต int สาธารณะ = 4331; Public TextField Statustext = New TextField ("โปรดเชื่อมต่อกับเซิร์ฟเวอร์!"); public firthread firthread = new firthread (นี่); public firpad () {setSize (440, 440); setlayout (null); Fetbackground (color.light_gray); addmouselistener (นี่); เพิ่ม (Statustext); Statustext.setBounds (สี่เหลี่ยมผืนผ้าใหม่ (40, 5, 360, 24)); Statustext.setEditable (เท็จ); } // เชื่อมต่อกับโฮสต์สาธารณะบูลีน ConnectServer (String Serverip, Int Serverport) พ่นข้อยกเว้น {ลอง {// รับพอร์ตโฮสต์ chesssocket = ซ็อกเก็ตใหม่ (Serverip, Serverport); // รับอินพุตสตรีม inputData = ใหม่ datainputStream (achesssocket.getInputStream ()); // get outputData = ใหม่ dataOutputStream (chesssocket.getOutputStream ()); firthread.start (); กลับมาจริง; } catch (ioexception ex) {statustext.settext ("การเชื่อมต่อล้มเหลว! /n"); } return false; } // ตั้งค่าสถานะบอร์ดเมื่อชนะโมฆะสาธารณะ setVicStatus (int vicchessColor) {// ล้างบอร์ด this.removeAll (); // ตั้งค่าตำแหน่งหมากรุกสีดำเป็นศูนย์สำหรับ (int i = 0; i <= ChessBlackCount; i ++) {chessblack_xpos [i] = 0; chessblack_ypos [i] = 0; } // ตั้งค่าตำแหน่งของหมากรุกสีขาวเป็นศูนย์สำหรับ (int i = 0; i <= achwhitecount; i ++) {chesswhite_xpos [i] = 0; chesswhite_ypos [i] = 0; } // ล้างจำนวนหมากรุกสีดำบนกระดาน chessblackCount = 0; // ล้างจำนวนหมากรุกสีขาวบนกระดาน chesswhitecount = 0; เพิ่ม (Statustext); Statustext.setBounds (40, 5, 360, 24); if (VicChessColor == 1) {// Black Chess ชนะ ChessBlackVictimes ++; Statustext.settext ("Black, Black: White" + ChessblackVictimes + ":" + ChessWhiteVictimes + ", เกมรีสตาร์ท, รอสีขาว ... "); } อื่นถ้า (VicChessColor == -1) {// หมากรุกสีขาวชนะ ChessWhiteVictimes ++; Statustext.settext ("Black: White" + ChessblackVictimes + ":" + ChessWhiteVictimes + ", เกมรีสตาร์ท, รอสีดำ ... "); }} // รับตำแหน่งของชิ้นส่วนหมากรุกที่ระบุโมฆะสาธารณะ setLocation (int xpos, int ypos, int chesscolor) {ถ้า (ChessColor == 1) {// เมื่อชิ้นหมากรุกเป็นสีดำ, chessblack_xpos [ChessblackCount] = xpos * 20; ChessBlack_ypos [ChessBlackCount] = YPOS * 20; ChessblackCount ++; } อื่นถ้า (ChessColor == -1) {// เมื่อชิ้นหมากรุกเป็นสีขาว, chesswhite_xpos [chesswhitecount] = xpos * 20; ChessWhitecount ++; }} // พิจารณาว่าสถานะปัจจุบันเป็นสถานะของรัฐที่ชนะการตรวจสอบบูลีนสาธารณะ (int xpos, int ypos, int chesscolor) {int chesslinkedCount = 1; // จำนวนการเชื่อมต่อ chesslinkedCompare = 1; // ใช้เพื่อเปรียบเทียบว่าคุณต้องการสำรวจชิ้นส่วน chessTocompareIndex = 0; // ตำแหน่งดัชนีของชิ้นส่วนที่จะเปรียบเทียบ int closeGrid = 1; // ตำแหน่งของกริดที่อยู่ติดกันถ้า (ChessColor == 1) {// ChessLinkedCount = 1; // หากนับชิ้นหมากรุกตัวเองจำนวนการเชื่อมต่อเริ่มต้นคือ 1 // แต่ละคู่ของคำสั่งลูปด้านล่างเป็นกลุ่มเนื่องจากตำแหน่งของช่วงเวลาถัดไปสามารถอยู่ตรงกลางได้มากกว่าที่ปลายทั้งสองข้าง ChessTocompareIndex ++) {// ถ่ายโอนผ่านชิ้นหมากรุกสีดำทั้งหมดบนกระดานถ้า ((((xpos+closegrid) * 20 == chessblack_xpos [ChessTocompareIndex]) && ((ypos * 20) == Chessblack_ypos = ChesslinkedCount + 1; // เพิ่ม 1 ถึงจำนวนการเชื่อมต่อถ้า (ChesslinkedCount == 5) {// เมื่อมีการเชื่อมต่อห้าชิ้นชัยชนะจะกลับมาเป็นจริง }}}} if (ChessLinkEdCount == (ChessLinkedCompare+1)) {ChessLinkedCompare ++; } else {// ถ้ามีชิ้นหมากรุกอยู่ตรงกลางที่ไม่ใช่สีดำมันจะเข้าสู่สาขานี้และไม่จำเป็นต้องสำรวจการหยุดพักอีกครั้งในเวลานี้; }} สำหรับ (closeGrid = 1; closeGrid <= 4; closeGrid ++) {สำหรับ (ChessTocompareIndex = 0; ChessTocompareIndex <= ChessBlackCount; ChessTocompareIndex ++) chessblack_ypos [ChessTocompareIndex])) {// พิจารณาว่าชิ้นหมากรุกทั้งสี่ทางด้านซ้ายของการเล่น ChesslinkedCount ++ หรือไม่; if (chesslinkedCount == 5) {return true; }}}} if (ChessLinkEdCount == (ChessLinkedCompare+1)) {ChessLinkedCompare ++; } else {break; }} // เมื่อเข้าสู่ชุดใหม่สำหรับลูปรีเซ็ตจำนวนการเชื่อมต่อ ฯลฯ ChesslinkedCount = 1; ChesslinkedCompare = 1; สำหรับ (closeGrid = 1; closeGrid <= 4; closeGrid ++) {สำหรับ (ChessTocompareIndex = 0; ChessTocompareIndex <= ChessBlackCount; ChessTocompareIndex ++) {ถ้า ((xpos * 20 == chessblack_xpos chessblack_ypos [ChessTocompareIndex])) {// พิจารณาว่า 4 ชิ้นสูงสุดของการเล่น ChesslinkedCount ++ หรือไม่; if (chesslinkedCount == 5) {return true; }}} if (ChessLinkEdCount == (ChessLinkedCompare+1)) {ChessLinkedCompare ++; } else {break; }} สำหรับ (closeGrid = 1; closeGrid <= 4; closeGrid ++) {สำหรับ (ChessTocompareIndex = 0; ChessTocompareIndex <= ChessBlackCount; ChessTocompareIndex ++) {if (xpos * 20 == Chessblack_xpos chessblack_ypos [ChessTocompareIndex])) {// พิจารณาว่าสี่ชิ้นด้านล่างของ ChesslinkedCount ++ ที่เล่นอยู่ในปัจจุบันหรือไม่; if (chesslinkedCount == 5) {return true; }}} if (ChessLinkEdCount == (ChessLinkedCompare+1)) {ChessLinkedCompare ++; } else {break; }} ChessLinkedCount = 1; ChesslinkedCompare = 1; สำหรับ (closeGrid = 1; closeGrid <= 4; closeGrid ++) {สำหรับ (chessTocompareIndex = 0; chessTocompareIndex <= chessblackCount; ChessTocompareIndex ++) {ถ้า (((xpos - ปิด) * 20 == chessblack_ypos [ChessTocompareIndex])) {// กำหนดว่าชิ้นส่วนหมากรุกทั้งสี่ในทิศทางด้านบนของการเล่น ChesslinkedCount ++ ในปัจจุบัน }} สำหรับ (closeGrid = 1; closeGrid <= 4; closeGrid ++) {สำหรับ (ChessTocompareIndex = 0; ChessTocompareIndex <= ChessBlackCount; ChessTocompareIndex ++) 20 == ChessBlack_ypos [ChessTocompareIndex])) {// ตรวจสอบว่าชิ้นส่วนหมากรุกทั้งสี่ในทิศทางขวาล่างของชิ้นส่วนหมากรุกในปัจจุบันคือ Black ChesslinkedCount ++; } else {break;}} chesslinkedCount = 1; ChessBlack_XPOS [ChessTocompareIndex]) && ((YPOS+CloseGrid) * 20 == ChessBlack_ypos [ChessTocompareIndex])) {// กำหนดว่าชิ้นส่วนของหมากรุกในทิศทางขวาของชิ้นส่วนที่ถูกต้อง (ChesslinkedCount == (ChesslinkedCompare+1)) {chesslinkedCompare ++; (((XPOS - CloseGrid) * 20 == ChessBlack_XPOS [ChessTocompareIndex]) && ((YPOS - CloseGrid) * 20 == ChessBlack_ypos [ChessTocompareIndex]) {// กำหนดว่าชิ้นส่วนหมากรุกทั้งสี่ กลับมา; (ChessTocompareIndex = 0; ChessTocompareIndex <= ChessWhitecount; ChessTocompareIndex ++) {ถ้า (((xpos+CloseGrid) * 20 == ChessWhite_XPOS [ChessTocompareIndex] ของการเล่น chesslinkedcount ++; (ChessTocompareIndex = 0; ChessTocompareIndex <= ChessWhitecount; ChessTocompareIndex ++) {ถ้า (((xpos - CloseGrid) * 20 == ChessWhite_XPOS [ChessTocompareIndex] ของการเล่น chesslinkedcount ++; <= 4; CloseGrid ++) {สำหรับ (ChessTocompareIndex = 0; ChessTocompareIndex <= ChessWhitecount; chesswhite_ypos [ChessTocompareIndex])) {// กำหนดว่า 4 ชิ้นส่วนบนของการเล่น chesslinkedcount ++; (CloseGrid = 1; CloseGrid <= 4; CloseGrid ++) {สำหรับ (ChessTocompareIndex = 0; ChessTocompareIndex <= ChessWhitecount; ChessTocompareIndex ++) {ถ้า ((XPOS * 20 == Chesshite_xpos chesswhite_ypos [ChessTocompareIndex])) {// กำหนดว่าสี่ชิ้นที่เล่นอยู่ในขณะนี้ ChesslinkedCount ++; ChesslinkedCount = 1; Chesswhite_xpos [ChessTocompareIndex]) && ((YPOS+CloseGrid) * 20 == ChessWhite_ypos [ChessTocompareIndex])) {// กำหนดว่าทั้ง 4 ชิ้นในทิศทางซ้ายของชิ้นส่วนหมากรุกเป็นสีขาว (ChesslinkedCount == (ChesslinkedCompare+1)) {chesslinkedCompare ++; (((xpos+closegrid) * 20 == chesswhite_xpos [chesstocompareindex]) && ((ypos - closegrid) * 20 == chesswhite_ypos [chesstocompareindex])) กลับมา; ChessTocompareIndex <= ChessWhitecount; ชิ้นส่วนหมากรุกคือ White ChesslinkedCount ++; (ChessTocompareIndex = 0; ChessTocompareIndex <= ChessWhitEcount; ChessTocompareIndex ++) {ถ้า (((xpos - CloseGrid) * 20 == ChessWhite_xpos [ChessTocompareIndex]) && สี่ชิ้นในทิศทางซ้ายของการเล่น chesslinkedcount ++; สี (กราฟิก G) {สำหรับ (int i = 40; i <= 380; i = i + 20) {G.Drawline (40, i, 400, i); 400, 400); // วาด chesspawn paintfirpoint (int xpos, int ypos, int chesscolor) {firpointblack firpblack = firpointblack ใหม่ (นี่); ChessColor); // เพิ่มชิ้นส่วนหมากรุกลงในบอร์ด firpblack.setbounds (xpos * 20 - 7, ypos * 20 - 7, 16, 16); ไม่สามารถใช้งานได้} else {// ชนะสถานะ firthread.sendmessage (" /" + chesspeername + " /หมากรุก" + xpos + "" + ypos + "" chesscolor); วิธีการชัยชนะและพารามิเตอร์ที่ผ่านมาเป็น Black Chess Victory Ismouseenabled = False; firthread.sendmessage (" /" + chesspeername + " /chess" + xpos + "" + ypos + "" + chesscolor); XPOS + "" YPOS + "เป็นตาข่ายของ Black"); 7, 16, 16); firpointwhite (นี้); 16); Statustext.settext ("Black (Thread" + ChessblackCount + "ขั้นตอน)" + XPOS + "" + YPOS + "มันคือสแควร์สีขาว"); firpblack.setbounds (xpos * 20 - 7, ypos * 20 - 7, 16, 16); FirpWhite.SetBounds (XPOS * 20 - 7, YPOS * 20 - 7, 16, 16); + Chesscolor); InputEvent.Button1_Mask) {chessx_pos = (int) e.getx (); chessy_pos / 20> 19) {// ไม่มีการกระทำเมื่อตำแหน่งหมากรุกไม่ถูกต้อง} else {paintfirpoint (a, b, chesscolor); โมฆะ mouseclicked (MouseEvent E) {} โมฆะสาธารณะ ActionPerformed (ActionEvent E) {}} 4. พัฒนาหม้อบอร์ดเธรด
นำเข้า java.util.stringTokenizer; นำเข้า java.io.ioException; /*** สร้างโดยผู้ดูแลระบบเมื่อปี 2016/11/21 */ คลาสสาธารณะ FirThread ขยายเธรด {firpad currpad; // คณะกรรมการหมากรุกของกระทู้ปัจจุบัน public firthread (firpad currpad) {this.currpad = currpad; } // ประมวลผลโมฆะข้อมูลสาธารณะที่ได้รับการจัดการ (สตริง msgreceived) {ถ้า (msgreceived.startswith ("/หมากรุก")) {// ข้อมูลที่ได้รับคือ chess StringTokenizer usermsgToken = new StringTokenizer // อาร์เรย์ของชิ้นส่วนหมากรุกและ 0 ดัชนีคือ: x พิกัด; 1 ดัชนีบิต: y พิกัด; 2 ดัชนีบิต: ChessInfo = {"-1", "-1", "0"}; int i = 0; // ธงบิตสตริง chessinfotoken; ในขณะที่ (usermsgtoken.hasmoretokens ()) {chessinfotoken = (สตริง) usermsgtoken.nexttoken (""); if (i> = 1 && i <= 3) {ChessInfo [i - 1] = ChessInFotoken; } i ++; } currpad.paintnetfirpoint (integer.parseint (chessinfo [0]), จำนวนเต็ม. parseint (chessinfo [1]), integer.parseint (Chessinfo [2])); } อื่นถ้า (msgreceived.startswith ("/yourname")) {// ข้อความที่ได้รับถูกเปลี่ยนชื่อ currpad.chessselfname = msgreceived.substring (10); } อื่นถ้า (msgreceived.equals ("/ข้อผิดพลาด")) {// ข้อความแสดงข้อผิดพลาดที่ได้รับคือ currpad.statustext.settext ("ผู้ใช้ไม่มีอยู่โปรดเข้าร่วมอีกครั้ง!"); }} // ส่งข้อความโมฆะสาธารณะ sendMessage (สตริง sndmessage) {ลอง {currpad.outputData.writeUtf (sndMessage); } catch (Exception ea) {ea.printstacktrace () ;; }} โมฆะสาธารณะเรียกใช้ () {สตริง msgreceived = ""; ลอง {ในขณะที่ (จริง) {// รอข้อมูลอินพุต msgreceived = currpad.inputData.ReadUtf (); GEALWITHMSG (MSGRECEIVEND); }} catch (ioexception es) {}}} เริ่มพัฒนาโมดูลเซิร์ฟเวอร์ด้านล่าง
1. พัฒนาแผงข้อมูลเซิร์ฟเวอร์
นำเข้า Java.awt.BorderLayout; นำเข้า Java.awt.Color; นำเข้า java.awt.flowlayout; นำเข้า java.awt.label; นำเข้า Java.awt.Panel; นำเข้า Java.awt.TextArea; นำเข้า Javax.swing.jlabel; /*** สร้างโดยผู้ดูแลระบบเมื่อปี 2016/11/21 */ คลาสสาธารณะ ServerMsGPanel ขยายพาเนล {Public Textarea msgtextarea = textarea ใหม่ ("", 22, 50, textarea.scrollbars_vertical_only); Public JLabel Statuslabel = new JLabel ("การเชื่อมต่อปัจจุบัน:", label.left); แผงสาธารณะ msgpanel = แผงใหม่ (); Public Panel StatusPanel = NEW PANEL (); Public ServerMsgPanel () {setSize (350, 300); Fetbackground (color.light_gray); SetLayout (New BorderLayout ()); msgpanel.setLayout (ใหม่ flowlayout ()); msgpanel.setsize (210, 210); StatusPanel.SetLayout (New BorderLayout ()); StatusPanel.Setsize (210, 50); msgpanel.add (msgtextarea); StatusPanel.Add (StatusLabel, BorderLayout.west); เพิ่ม (msgpanel, borderlayout.center); เพิ่ม (stationsPanel, BorderLayout.north); - 2. พัฒนากระบวนการเซิร์ฟเวอร์
นำเข้า java.io.datainputstream; นำเข้า Java.io.DataOutputStream; นำเข้า java.io.ioException; นำเข้า java.net.socket; นำเข้า Java.util.enumeration; นำเข้า java.util.hashtable; นำเข้า java.util.stringTokenizer; /*** สร้างโดยผู้ดูแลระบบเมื่อปี 2016/11/21 */ คลาสสาธารณะ FIRSERVERTHREAD ขยายเธรด {Socket CrientSocket; // บันทึกข้อมูลซ็อกเก็ตไคลเอนต์ hashtable clientdatahash; // บันทึก hash hashtable clientNameHash ที่สอดคล้องกับพอร์ตไคลเอนต์และสตรีมเอาต์พุต // บันทึก Hash Hashtable ChesspeerHash ที่สอดคล้องกับซ็อกเก็ตไคลเอ็นต์และชื่อไคลเอนต์; // บันทึก Hash ServerMsGPanel ที่สอดคล้องกับผู้สร้างเกมและผู้เข้าร่วมเกม บูลีน isClientClosed = false; Public FirserverThread (Socket ClientSocket, hashtable clientdatahash, hashtable clientNameHash, Hashtable ChessPeerHash, เซิร์ฟเวอร์ ServerMSGPANEL) {this.ClientSocket = ClientSocket; this.clientDatahash = clientDatahash; this.clientNameHash = clientNameHash; this.chesspeerhash = ChessPeerHash; this.servermsgPanel = เซิร์ฟเวอร์; } โมฆะสาธารณะ GEALWITHMSG (สตริง mSgreCeived) {String clientName; Peername String; if (msgreceived.startswith ("/")) {ถ้า (msgreceived.equals ("/list")) {// ข้อมูลที่ได้รับคือการอัปเดตข้อเสนอแนะรายการผู้ใช้ (getUserList ()); } อื่นถ้า (msgreceived.startswith ("/creatgame [inchess]")) {// ข้อความที่ได้รับคือการสร้างสตริงเกม gamecreaterame = msgreceived.substring (20); // รับชื่อเซิร์ฟเวอร์ที่ซิงโครไนซ์ (clientNameHash) {// ใส่พอร์ตผู้ใช้ในรายการผู้ใช้ ClientNameHash.put (ClientSocket, msgreceived.substring (11)); } ซิงโครไนซ์ (ChessPeerHash) {// ตั้งค่าโฮสต์เป็นสถานะการรอ chesspeerhash.put (gamecreername, "Wait"); } ข้อเสนอแนะ ("/yourName" + clientNameHash.get (clientSocket)); sendgamepeermsg (gamecreername, "/ok"); SendPublicMSG (getUserList ()); } อื่นถ้า (msgreceived.startswith ("/joingame")) {// ข้อความที่ได้รับคือเมื่อเข้าร่วมเกม StringTokenizer usertokens = new StringTokenizer (msgreceived, ""); String usertoken; String Gamecreatorname; String gamepaticipantName; สตริง [] playerNames = {"0", "0"}; int nameindex = 0; ในขณะที่ (usertokens.hasmoretokens ()) {usertoken = (สตริง) 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 ("รอ")) {// เกมถูกสร้างขึ้นซิงโครไนซ์ (clientnamehash) {// เพิ่มลูกค้าที่เกี่ยวข้อง } ซิงโครไนซ์ (chesspeerhash) {// เพิ่มหรือแก้ไข chesspeerhash.put ที่เกี่ยวข้อง (gamecreatorname, gamepaticipantname); } sendPublicMSG (getUserList ()); // ส่งข้อความไปยังผู้เข้าร่วมเกม sendgamepeermsg (gamepaticipantname, ("/peer" + "[inchess]" + gamecreatorname)); // ส่งเกมไปยังผู้สร้างเกม sendgamepeermsg (gamecreatorname, ("/peer" + "[inchess]" + gamepaticipantname)); } else {// ถ้าเกมไม่ได้สร้างเกมจะถูกปฏิเสธที่จะเพิ่ม sendGamePeerMsg (gamepaticipantName, "/ปฏิเสธ"); ลอง {closeclient (); } catch (Exception ez) {ez.printstacktrace (); }}} อื่นถ้า (msgreceived.startswith ("/[inchess]")) {// ข้อความที่ได้รับคือ int firstLocation = 0, lastLocation; lastLocation = msgreceived.indexof ("", 0); peername = msgreceived.substring ((FirstLocation + 1), LastLocation); msgreceived = msgreceived.substring ((lastlocation + 1)); if (sendgamepeermsg (peername, msgreceived)) {คำติชม ("/ข้อผิดพลาด"); }} อื่นถ้า (msgreceived.startswith ("/giveup")) {// ข้อความที่ได้รับคือเมื่อคุณยอมแพ้สตริงเกม chessClientName = msgreceived.substring (8); if (chesspeerhash.containskey (chessClientName) &&! ((String) chesspeerhash.get (ChessClientName)) .Equals ("รอ")) {// ผู้ชนะคือผู้เข้าร่วมเกม ซิงโครไนซ์ (ChessPeerHash) {// ลบผู้ใช้ออกจากเกม ChessPeerHash.Remove (chessClientName); }} if (chesspeerhash.containsvalue (ChessClientName)) {// ผู้ชนะคือผู้สร้างเกมและส่งข้อความชัยชนะ SendGamePeermsg ((String) Gethashkey (Chesspeerhash, ChessClientName) ซิงโครไนซ์ (ChessPeerHash) {// ลบผู้ใช้ออกจากเกม ChessPeerHash.Remove ((String) Gethashkey (ChesspeerHash, ChessClientName)); }}} else {// เมื่อข้อมูลที่ได้รับคือข้อมูลอื่น ๆ int lastLocation = msgreceived.indexof ("", 0); if (lastLocation == -1) {คำติชม ("คำสั่งไม่ถูกต้อง"); กลับ; }}} else {msGreceived = clientNameHash.get (clientsocket) + ">" + msgreceived; ServerMsgPanel.msgtextarea.append (msgreceived + "/n"); SendPublicMSG (msgreceived); servermsgpanel.msgtextarea.setCaretPosition (servermsgpanel.msgtextarea.getText () .length ()); }} // ส่งโมฆะสาธารณะ sendPublicMSG (สตริง publicmsg) {ซิงโครไนซ์ (clientDatahash) {สำหรับ (การแจงนับ enu = clientDatahash.Elements (); enu .HasmoreElements ();) {dataOutputStream outputData = ลอง {outputData.writeUtf (publicmsg); } catch (ioexception es) {es.printstacktrace (); }}}}} // ส่งข้อมูลไปยังผู้ใช้ในเกมสาธารณะที่ระบุ SendGamePeermsg (สตริง gamepeertarget, สตริง gamepeermsg) {สำหรับ (enumeration enu = clientdatahash.keys (); enu.hasmorelements () enu.nextelement (); if (gamepeertarget.equals ((String) clientNameHash.get (userClient)) &&! gamepeertarget.equals ((สตริง) clientnamehash .get (clientsocket))) {// synchronized (clientDatahash) {// ลอง {// ส่งข้อมูล peeroutdata.writeutf (gamepeermsg); } catch (IOException es) { es.printStackTrace(); } } return false; }} ส่งคืนจริง; } // 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 Goziches client"); Feedback("/list --update user list"); Feedback("/<username> <talk> --private chat"); Feedback("Note: the command must be sent to all users"); } public void closeClient() { serverMsgPanel.msgTextArea.append("User disconnected:" + clientSocket + "/n"); synchronized (chessPeerHash) { //If it is a game client host 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) { // Delete customer data clientDataHash.remove(clientSocket); } synchronized (clientNameHash) { // Delete customer data clientDataHash.remove(clientSocket); } synchronized (clientNameHash) { // Delete customer data clientNameHash.remove(clientSocket); } sendPublicMsg(getUserList()); serverMsgPanel.statusLabel.setText("Current connections:" + clientDataHash.size()); try { clientSocket.close(); } catch (IOException exx) { exx.printStackTrace(); } isClientClosed = true; } public void run() { DataInputStream inputData; synchronized (clientDataHash) { serverMsgPanel.statusLabel.setText("Current connections:" + clientDataHash.size()); } try { // Wait for information to connect to the host 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("Clear List"); JButton serverStatusButton = new JButton("Server Status"); JButton closeServerButton = new JButton("Shunt down the server"); Panel buttonPanel = new Panel(); ServerMsgPanel serverMsgPanel = new ServerMsgPanel(); ServerSocket serverSocket; Hashtable clientDataHash = new Hashtable(50); //Bind client socket and output stream Hashtable clientNameHash = new Hashtable(50); //Bind client socket and client name Hashtable chessPeerHash = new Hashtable(50); //Bind the game creator and game joiner public FIRServer() { super("Java Goji Server"); 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); } }); หีบห่อ(); setVisible(true); setSize(400, 300); setResizable(false); ตรวจสอบความถูกต้อง(); try { createServer(4331, serverMsgPanel); } catch (exception e) {e.printstacktrace (); } } // Create server with specified ports and panels public void createServer(int port, ServerMsgPanel serverMsgPanel) throws IOException { Socket clientSocket; // Client socket long clientAccessNumber = 1; // The number of clients connected to the host this.serverMsgPanel = serverMsgPanel; // Set the current host try { serverSocket = new ServerSocket(port); serverMsgPanel.msgTextArea.setText("Server started at:" + InetAddress.getLocalHost() + ":" //djr + serverSocket.getLocalPort() + "/n"); while (true) { // Listen to the information of the client socket clientSocket = serverSocket.accept(); serverMsgPanel.msgTextArea.append("Connected user:" + clientSocket + "/n"); // Create client output stream DataOutputStream outputData = new DataOutputStream(clientSocket .getOutputStream()); // Bind client socket and output stream clientDataHash.put(clientSocket, outputData); // Bind client socket and client name clientNameHash .put(clientSocket, ("New Player" + clientAccessNumber++)); // Create and run the server-side thread 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) { // Clear server information serverMsgPanel.msgTextArea.setText(""); } if (e.getSource() == serverStatusButton) { // Show server information try { serverMsgPanel.msgTextArea.append("Server Information:" + InetAddress.getLocalHost() + ":" + serverSocket.getLocalPort() + "/n"); } catch (Exception ee) { ee.printStackTrace(); } } if (e.getSource() == closeServerButton) { // Close the server 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.*; นำเข้า 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 { // Client socket Socket clientSocket; // Data input stream DataInputStream inputStream; // Data output stream DataOutputStream outputStream; // Username String chessClientName = null; // Host address String host = null; // Host port int port = 4331; // Whether you are chatting boolean isOnChat = false; // Whether you are playing chess boolean isOnChess = false; // Whether the game is in progress boolean isGameConnected = false; // Whether it is the game creator boolean isCreator = false; // Whether it is the game entrant boolean isParticipant = false; // User List area UserListPad userListPad = new UserListPad(); // User Chat area UserChatPad userChatPad = new UserChatPad(); // User Operation area UserControlPad userControlPad = new UserControlPad(); // User input area UserInputPad userInputPad = new UserInputPad(); // Chess area FIRPad firPad = new FIRPad(); // Panel southPanel = new Panel(); Panel northPanel = new Panel(); Panel centerPanel = new Panel(); Panel eastPanel = new Panel(); // Construct method to create interface public FIRClient() { super("Java Goji Client"); 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 in chat { // Close the client socket clientSocket.close(); } catch (Exception ed){} } if (isOnChess || isGameConnected) { // Try in chess { // Close the chess port firPad.chessSocket.close(); } catch (Exception ee){} } System.exit(0); } }); add(eastPanel, BorderLayout.EAST); add(centerPanel, BorderLayout.CENTER); add(southPanel, BorderLayout.SOUTH); หีบห่อ(); setSize(670, 560); setVisible(true); setResizable(false); this.validate(); } // Connect to the server according to the specified IP address and port public boolean connectToServer(String serverIP, int serverPort) throws Exception { try { // Create client socket clientSocket = new Socket(serverIP, serverPort); // Create input stream inputStream = new DataInputStream(clientSocket.getInputStream()); // Create outputStream = new DataOutputStream(clientSocket.getOutputStream()); // Create client thread FIRClientThread clientthread = new FIRClientThread(this); // Start the thread and wait for chat information clientthread.start(); isOnChat = true; กลับมาจริง; } catch (IOException ex) { userChatPad.chatTextArea .setText("Cannot connect!/n"); } return false; } // Client event handling public void actionPerformed(ActionEvent e) { if (e.getSource() == userControlPad.connectButton) { // Connect to the host button click event host = firPad.host = userControlPad.ipInputted.getText(); // Get the host address try { if (connectToServer(host, port)) { // When successfully connecting to the host, set the corresponding interface status of the client userChatPad.chatTextArea.setText(""); userControlPad.connectButton.setEnabled(false); userControlPad.createButton.setEnabled(true); userControlPad.joinButton.setEnabled(true); firPad.statusText.setText("Connection successful, please wait!"); } } catch (Exception ei) { userChatPad.chatTextArea .setText("Cannot connect!/n"); } } if (e.getSource() == userControlPad.exitButton) { // Leave the game button click event if (isOnChat) { // If the user is in a chat state try { // Close the client socket clientSocket.close(); } catch (Exception ed){} } if (isOnChess || isGameConnected) { // If the user is in the game state try { // Close the game port firPad.chessSocket.close(); } catch (Exception ee){} } System.exit(0); } if (e.getSource() == userControlPad.joinButton) { // Join the game button click event String selectedUser = (String)userListPad.userList.getSelectedItem(); // Get the game to be joined if (selectedUser == null || selectedUser.startsWith("[inchess]") || selectedUser.equals(chessClientName)) { // If the user to be joined is not selected, or the selected user is already in the game, a prompt message is given for firPad.statusText.setText("A user must be selected!"); } else { // Perform the operation of joining the game try { if (!isGameConnected) { // If the game socket is not connected if (firPad.connectServer(firPad.host, firPad.port)) { // If the connection to the host is successful 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 { // If 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("Cannot connect: /n" + ee); } } } } if (e.getSource() == userControlPad.createButton) { // Create game button click event try { if (!isGameConnected) { // If the game port is not connected if (firPad.connectServer(firPad.host, firPad.port)) { // If the connection to the host is successful 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 { // If the game port is connected 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("Cannot connect: /n" + ec); } } if (e.getSource() == userControlPad.cancelButton) { // Exit the game button click event 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("Please create or add the game!"); } if (!isOnChess) { // non-game userControlPad.createButton.setEnabled(true); userControlPad.joinButton.setEnabled(true); userControlPad.cancelButton.setEnabled(false); firPad.statusText.setText("Please create or join the game!"); } isParticipant = isCreator = false; } } public void keyPressed(KeyEvent e) { TextField inputwords = (TextField) e.getSource(); if (e.getKeyCode() == KeyEvent.VK_ENTER) { // Handle the carriage enter key event if (userInputPad.userChoice.getSelectedItem().equals("all users")) { // Send a message to everyone try { // Send a message outputStream.writeUTF(inputwords.getText()); inputwords.setText(""); } catch (Exception ea) { userChatPad.chatTextArea .setText("Cannot connect to the server!/n"); userListPad.userList.removeAll(); userInputPad.userChoice.removeAll(); inputwords.setText(""); userControlPad.connectButton.setEnabled(true); } } else { // Send a message to the designated person try { outputStream.writeUTF("/" + userInputPad.userChoice.getSelectedItem() + " " + inputwords.getText()); inputwords.setText(""); } catch (Exception ea) { userChatPad.chatTextArea .setText("Cannot connect to the server!/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){} } }至此,网络版五子棋就算是开发完成了。关于这么多类和包的关系如下图:
ข้างต้นเป็นเนื้อหาทั้งหมดของบทความนี้ I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.