Artikel ini membagikan kode spesifik untuk Implementasi Java GOZIQI Versi Online untuk referensi Anda. Konten spesifiknya adalah sebagai berikut
Analisis Persyaratan:
Untuk goji online, fungsi -fungsi berikut perlu ditambahkan berdasarkan goji biasa:
1. Memiliki sisi server dan klien. Setelah pengguna masuk ke server melalui klien, mereka dapat bermain game dengan pengguna yang masuk lainnya.
2. Server mendukung beberapa grup pengguna untuk bermain game secara bersamaan
3. Pengguna dapat membuat game baru di server atau bergabung dengan game yang dibuat
4. Pengguna dapat mengobrol dan berkomunikasi saat bermain catur
Dari yang di atas, kita dapat mengetahui fungsi yang perlu diimplementasikan:
・ Menyediakan fungsi server dan klien
・ Server akan memantau status login klien dan memungkinkan banyak klien untuk masuk
・ Pengguna dapat masuk ke server melalui klien, dan kemudian mereka dapat melihat pengguna lain dari server saat ini online dan mengobrol dengan mereka, dll.
・ Setelah masuk ke server, pengguna dapat membuat game Gozi baru atau bergabung dengan game Gozi yang dibuat.
・ Pengguna dapat bermain game dengan pengguna lain seperti Goji biasa melalui klien
Menurut fungsinya, Gochi jaringan dibagi menjadi 4 modul: yaitu modul panel pengguna, modul panel papan, modul server gochi, dan modul klien gochi
Mari kita mulai menyusun modul panel pengguna:
1. Kembangkan panel daftar pengguna
impor java.awt.*; /*** Dibuat oleh Administrator pada 2016/11/21. */// Dalam keadaan awal, 10 informasi bernama "Tidak ada pengguna" akan ditambahkan ke daftar, menunjukkan bahwa server mendukung hingga 10 pengguna secara online pada saat yang sama.// Daftar ditambahkan ke panel, menggunakan format tata letak Kelas Public Format Kelas Publik Extends Panel {Public List UserList = New List (10); UserListPad publik () {setLayout (borderlayout baru ()); untuk (int i = 0; i <10; i ++) {userlist.add (i+"."+"Tidak ada pengguna"); } add (userList, borderlayout.center); }} 2. Kembangkan panel obrolan pengguna
impor javax.swing.*; impor java.awt.*; /*** Dibuat oleh Administrator pada 2016/11/21. */// Panel obrolan adalah kontrol tampilan TextArea dengan bilah gulir vertikal. // TexTarea ditambahkan ke panel, menggunakan format tata letak "BorderLayout". Public Class UserChatPad memperluas jpanel {public jTextArea chattextarea = baru jTextArea ("Area Perintah", 18,20); Public UserChatPad () {setLayout (BorderLayout baru ()); chattextarea.setautoscrolls (true); chattextarea.setlinewrap (true); add (chattextArea, borderlayout.center); }} 3. Kembangkan panel input pengguna
impor javax.swing.*; impor java.awt.*; /*** Dibuat oleh Administrator pada 2016/11/21. */// Panel berisi dua kontrol tampilan // ContentInPitted adalah kontrol TextField, di mana pengguna dapat memasukkan informasi obrolan kelas publik UserInputPad memperluas jpanel {public jTextField contentInputted = new jTextField ("", 26); Public JComboBox UserChoice = new jcomboBox (); UserInputPad () {setLayout (FlowLayout baru (flowlayout.left)); untuk (int i = 0; i <50; i ++) {userchoice.additem (i+"."+"no user"); } userchoice.setsize (60,24); Tambahkan (UserChoice); tambahkan (contentInputted); }} 4. Kembangkan Panel Operasi Pengguna
impor javax.swing.*; impor java.awt.*; /*** Dibuat oleh Administrator pada 2016/11/21. */ kelas publik UserControlpad memperluas jpanel {public jlabel ipplabel = new jlabel ("ip", jlabel.left); publik jTextField ipInputted = new jTextField ("localhost", 10); publik jbutton connectButton = jbutton baru ("Connect to Server"); publik jbutton createButton = jbutton baru ("create game"); publik jbutton joinbutton = jbutton baru ("gabung game"); public jbutton cancelButton = jbutton baru ("Game Up Game"); Public JButton ExitButton = JButton baru ("Game Keluar"); UserControlPad publik () {setLayout (flowlayout baru (flowlayout.left)); Securbackground (color.light_gray); tambahkan (iPlabel); tambahkan (ipinputted); Tambahkan (ConnectButton); Tambah (createButton); tambahkan (joinbutton); tambahkan (cancelButton); Tambahkan (ExitButton); }} Mulailah mengembangkan modul panel papan di bawah ini
1. Kembangkan catur hitam
impor java.awt.*; /*** Dibuat oleh Administrator pada 2016/11/21. */ kelas publik FirpointBlack memperluas Canvas {Firpad Padbelonged; // papan tempat catur hitam itu milik firpointblack publik (firpad padbelonged) {setsize (20, 20); // atur ukuran potongan catur this.padbelonged = Padbelonged; } public void cat (grafik g) {// menggambar catur catur g.setColor (color.black); G.Filloval (0, 0, 14, 14); }} 2. Kembangkan kategori catur putih
impor java.awt.*; /*** Dibuat oleh Administrator pada 2016/11/21. */ kelas publik Firpointwhite memperluas Canvas {firpad padbelonged; // Dewan tempat catur putih itu milik firpointwhite publik (firpad padbelonged) {setsize (20, 20); this.padbelonged = Padbelonged; } public void cat (grafik g) {// menggambar catur potongan g.setColor (color.white); G.Filloval (0, 0, 14, 14); }} 3. Kembangkan panel papan catur
impor java.awt.*; impor java.awt.event.*; impor java.io.*; impor java.net.*; impor javax.swing.jtextfield; /*** Dibuat oleh Administrator pada 2016/11/21. */ kelas publik Firpad memperluas panel mengimplementasikan MouseListener, ActionListener {// dapatkah mouse digunakan boolean publik ismouseenabled = false; // apakah akan memenangkan boolean publik iswinned = false; // apakah akan bermain catur public boolean isgaming = false; // x -sumbu koordinat bit dari potongan catur publik int chessx_pos = -1; // Y -AXIS Koordinat Bit dari potongan catur publik int chessy_pos = -1; // Warna potongan catur publik int chesscolor = 1; // black x-axis koordinat array bit publik int chessblack_xpos [] = int new [200]; // Black Y-Axis Koordinat Bit Array Public Int ChessBlack_ypos [] = int baru [200]; // White Y-Axis Koordinat Bit Array Public Int Chesswhite_xpos [] = int baru [200]; // catur putih Y-AXIS Koordinat Array Digit Public Int Chesswhite_ypos [] = int baru [200]; // Jumlah catur hitam public int chessblackcount = 0; // Jumlah catur putih int int chesswhitecount = 0; // Jumlah catur hitam menang publik int chessblackVictimes = 0; // Jumlah catur putih menang di depan umum caturwhitevictimes = 0; // Jumlah catur putih menang di depan umum caturwhitevictimes = 0; // antarmuka lengan soket publik catursocket; InputData Publik DataInputStream; DataOutputStream OutputData publik; public string chesselfname = null; public string chesspeerName = null; host string publik = null; port int publik = 4331; public textfield statustext = new TextField ("Harap terhubung ke server!"); Firthread Publik Publik = Firthread baru (ini); firpad publik () {setSize (440, 440); setLayout (null); Securbackground (color.light_gray); AddMouseListener (ini); Tambah (Statustext); statustext.setbounds (persegi panjang baru (40, 5, 360, 24)); statustext.seteditable (false); } // Sambungkan ke host public boolean connectServer (string serverip, int serverport) melempar pengecualian {coba {// dapatkan port host chesssocket = soket baru (serverip, serverport); // dapatkan input stream inputData = datainputStream baru (chiSsocket.getInputStream ()); // dapatkan outputData = DataOutputStream baru (Chesssocket.getoutputStream ()); firthread.start (); Kembali Benar; } catch (ioException ex) {statustext.setText ("Koneksi gagal! /n"); } return false; } // Tetapkan status papan saat memenangkan public void setVicStatus (int vicchesscolor) {// hapus papan this.removeall (); // Atur posisi catur hitam ke nol untuk (int i = 0; i <= chessblackcount; i ++) {chessblack_xpos [i] = 0; Chessblack_ypos [i] = 0; } // Atur posisi catur putih ke nol untuk (int i = 0; i <= chesswhitecount; i ++) {chesswhite_xpos [i] = 0; ChessWhite_ypos [i] = 0; } // Hapus jumlah catur hitam di papan caturblackcount = 0; // Bersihkan jumlah catur putih di papan caturwhitecount = 0; Tambah (Statustext); statustext.setbounds (40, 5, 360, 24); if (vicchesscolor == 1) {// catur hitam menang caturblackvictimes ++; statustext.setText ("Black, Black: White" + ChessBlackVictimes + ":" + ChessWhitevictimes + ", game restart, tunggu putih ..."); } lain jika (vicchesscolor == -1) {// catur putih menang caturwhitevictimes ++; statustext.setText ("Black: White" + ChessBlackVictimes + ":" + ChessWhitevictimes + ", game restart, tunggu hitam ..."); }} // Dapatkan posisi setlocation public public piece catur yang ditentukan (int xpos, int ypos, int chesscolor) {if (chiSscolor == 1) {// Ketika potongan catur hitam, chessblack_xpos [chessblackcount] = xpos * 20; Chessblack_ypos [ChessBlackCount] = ypos * 20; ChessBlackCount ++; } else if (chesscolor == -1) {// Saat potongan catur putih, chiSswhite_xpos [cyswhitecount] = xpos * 20; Chesswhitecount ++; }} // Tentukan apakah keadaan saat ini adalah negara pemenang boolean checkvicstatus (int xpos, int ypos, int chesscolor) {int chesslinkedcount = 1; // Jumlah CHESSLinkedCompare yang terhubung = 1; // Digunakan untuk membandingkan apakah Anda ingin terus melintasi bagian int chesstocompareIndex = 0; // Posisi indeks dari karya yang akan dibandingkan int closeGrid = 1; // Posisi kisi -kisi yang berdekatan if (cyscolor == 1) {// chesslinkedcount = 1; // Jika potongan catur itu sendiri dihitung, jumlah awal koneksi adalah 1 // setiap pasangan untuk pernyataan loop di bawah ini adalah sebuah kelompok, karena posisi periode berikutnya dapat berada di tengah daripada di kedua ujungnya untuk (closeGrid = 1; closeGrid <= 4; closeGrid ++) {// Transipate melalui 4 grid yang berdekatan untuk (cheesstocorc = cheess = cheess = cheess = chees = trasipasi 0; 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; // Tambahkan 1 ke jumlah koneksi IF (ChessLinkedCount == 5) {// Ketika lima bagian terhubung, kemenangan mengembalikan true; }}}} if (chesslinkedcount == (chiSslinkedCompare+1)) {cHessLinkedCompare ++; } else {// Jika ada bagian catur di tengah yang tidak hitam, itu akan memasuki cabang ini, dan tidak perlu melintasi istirahat lagi saat ini; }} for (closeGrid = 1; closeGrid <= 4; closeGrid ++) {for (chesstocompareIndex = 0; chesstocompareIndex <= chessblackcount; chesstocompareIndex ++) {if ((xpos - closeGrid) * 20 == chessblack_xpos {if ((xposs - closeD) * 20 == Chessblack_xpos (xpos) Chessblack_ypos [ChesstocompareIndex])) {// Tentukan apakah empat bagian catur di sebelah kiri ChessLinkedCount yang saat ini bermain ++; if (chesslinkedcount == 5) {return true; }}}} if (chesslinkedcount == (chiSslinkedCompare+1)) {cHessLinkedCompare ++; } else {break; }} // Saat memasukkan set baru untuk loop, setel ulang jumlah koneksi, dll. ChessLinkedCount = 1; ChessLinkedCompare = 1; untuk (closeGrid = 1; closeGrid <= 4; closeGrid ++) {for (chesstocompareIndex = 0; ChesstocompareIndex <= ChessBlackCount; ChesstocompareIndex ++) {if ((xpos * 20 == Chessblack_xpos [cesstocompareindex Chessblack_ypos [ChessTocompareIndex])) {// Tentukan apakah 4 bagian teratas dari ChessLinkedCount yang saat ini bermain ++; if (chesslinkedcount == 5) {return true; }}} if (chesslinkedcount == (chiSslinkedCompare+1)) {ChessLinkedCompare ++; } else {break; }} untuk (closeGrid = 1; closeGrid <= 4; closeGrid ++) {for (chesstocompareIndex = 0; chesstocompareIndex <= chessblackcount; chesstocompareIndex ++) {if (xpos * 20 == chessblack_xpos [chesstocare {if) (xpos * 20 == CHESSBLACK_XPOS [chesstocare (xpos * 20 == CHESSBLACK_XPOS [chesstocare (xpos * 20 = Chessblack_ypos [chiStocompareIndex])) {// Tentukan apakah empat bagian di bawah yang saat ini dimainkan ChessLinkedCount ++; if (chesslinkedcount == 5) {return true; }}} if (chesslinkedcount == (chiSslinkedCompare+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]) {// Tentukan apakah empat bagian catur di arah kiri atas dari ChessLinkedCount yang saat ini dimainkan ++} if (ChessLinkedCount == (CHESSLINKED; } } 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])) {// Tentukan apakah empat potongan catur di arah kanan bawah dari bagian catur saat ini adalah cyslinkedcount hitam ++} if (chesslinkedcount == 5) {return true; } else {break;}} ChessLinkedCount = 1; Chessblack_xpos [ChesstocompareIndex]) && ((ypos+closeGrid) * 20 == CHESSBLACK_YPOS [ChessTocompareIndex]) {// Tentukan apakah empat bagian catur {catur {ife {ife {ife {ife {Chesslink {Chesslink; (ChessLinkedCount == (ChessLinkedCompare+1)) {ChessLinkedCompare ++ (((XPOS - CloseGrid) * 20 == CHESSBLACK_XPOS [CHESSTOCompareIndex]) && ((YPOS - CloseGrid) * 20 == CHESSBLACK_YPOS [CHESSTOCOMPAREIndex]) {// Apakah empat potongan catur dalam arah kiri yang lebih rendah dari CHESS CHESSICE PIECED; Kembalikan true; (ChessTocompareIndex = 0; ChessTocompareIndex <= ChessWhitecount; ChesstocompareIndex ++) {if (((xpos+closeGrid) * 20 == CHESSWHITE_XPOS [CHESSTOCOMPAREDEX]) & & YPOS * 20 == CHESSWHITE_POS [CHESSOCOCE]) (YPOS * 20 == CHESSWHITE_YPOS [CHESSOCEDEX [ dari ChessLinkedCount saat ini ++; (ChessTocompareIndex = 0; ChessTocompareIndex <= ChessWhitecount; ChesstocompareIndex ++) {if (((xpos - closeGrid) * 20 == CHESSWHITE_XPOS [CHESSTOCOMPAREDEX]) & & YPOS * 20 == CHESSWHITE_POS [CHESSOCOCE]) (YPOS * 20 == CHESSWHITE_YPOS [CHESSOPOS)) (ypos * 20 == CHESSWHITE_POS [CHESSICEDEX [ dari ChessLinkedCount yang sedang diputar ++; <= 4; CloseGrid ++) {for (ChessTocompareIndex = 0; ChessTocompareIndex <= ChessWhitecount; ChessTocompareIndex ++) {if ((xpos * 20 == CHESSWHITE_XPOS [CHESSTOCompareIndex]) && (ypos+close. CHESSWHITE_YPOS [ChesstocompareIndex]) {// Tentukan apakah 4 bagian teratas dari ChessLinkedCount yang saat ini dimainkan ++} if (CHESSLINDCOUNT == (CHESTLINKED (CHESSLINK; (closeGrid = 1; closeGrid <= 4; closeGrid ++) {for (chesstocompareIndex = 0; chesstocompareIndex <= chesswhitecount; chesstocompareIndex ++) {if ((xpoS * 20 == chesswhite_xpos [cheStocompareindex])))) (cHessWhite_xpos [cheStocompareindex])))))) (= = = = cHessWhite_XPOS [cheStocompareindex])))))) (= = = cHessWhite_XPOS [cheStocompareindex])))))) (= = = cesswhite_xpos [cheStocompareIndex Chesswhite_ypos [ChesstocompareIndex]) {// Tentukan apakah empat bagian di bawah yang saat ini dimainkan ChessLinkedCount ++}}} {CHESSLINDCOUNT == (CHESSLINKEDCEDCEDCEDCEDCEDECE; ChessLinkedCount = 1; CHESSWHITE_XPOS [ChessTocompareIndex]) && ((ypos+closeGrid) * 20 == CHESSWHITE_YPOS [CHESSTOCOCOMPAREIDEX]) {// Tentukan apakah semua 4 bagian o. (ChessLinkedCount == (ChessLinkedCompare+1)) {ChessLinkedCompare ++ (((XPOS+CloseGrid) * 20 == CHESSWHITE_XPOS [CHESSTOCompareIndex]) && ((YPOS - CloseGrid) * 20 == CHESSWHITE_YPOS [ChesstocompareIndex]) {// Apakah empat piece (cHesstocompareInd) {// chat iFounk; Return True; ChessTocompareIndex <= ChessWhitecount; Potongan catur adalah CHESSLINKEDCOUNT ++; (ChessTocompareIndex = 0; ChessTocompareIndex <= ChessWhitecount; ChesstocompareIndex ++) {if (((xpos - closeGrid) * 20 == CHESSWHITE_XPOS [CHESSTOCompareIndex] && (YPOS -CLOSGRID) * 20 == CHESSHESSHEDEX]) (YPOS -CLOSGRID) * 20 == Empat bagian ke kiri bawah dari ChessLinkedCount yang saat ini dimainkan ++; Cat (grafik g) {untuk (int i = 40; i <= 380; i = i + 20) {g.drawline (40, i, 400, i); 400, 400); // Gambar cyspawn public void paintfirpoint (int xpos, int ypos, int chesscolor) {firpointblack firpblack = firpointblack baru (ini); CHESSCOLOR); // Tambahkan potongan catur ke papan firpblack.setbounds (xpos * 20 - 7, ypos * 20 - 7, 16, 16); tidak tersedia} {// Menang Firthread Metode kemenangan, dan parameter yang dilewati sebagai kemenangan catur hitam ismouseenabled = false; Firthread.SendMessage (" /" + ChesspeerName + " /CHESS" + XPOS + "" + YPOS + "" CHESSCOLOR); XPOS + " + YPOS +", giliran Black. "); - 7, 16); Firpointwhite (ini); 16); firpblack.setbounds (xpos * 20 - 7, ypos * 20 - 7, 16, 16); this.add (firpwhite); ChesspeerName + " /Victory" + ChessColor); (E.GetModifiers () == InputEvent.button1_mask) {Chessx_pos = (int) e.getx (); CHESSX_POS / 20> 19 || mouseExited (mouseEvent e) {} public void mouseclicked (mouseEvent e) {} public void actionPerformed (actionEvent e) {}} 4. Kembangkan utas papan catur
impor java.util.stringtokenizer; impor java.io.ioException; /*** Dibuat oleh Administrator pada 2016/11/21. */ Firthread kelas publik memperluas Thread {Firpad Currpad; // Papan catur utas saat ini Firthread Publik (Firpad Currpad) {this.currpad = Currpad; } // Memproses informasi yang diperoleh public void dealwithmsg (string msgrreved) {if (msgrreved.startswith ("/catur")) {// Informasi yang diterima adalah catur stringTokenizer usermsgToken = stringTokenizer baru (msgreceived, ""); // Array informasi potongan catur dan 0 indeks adalah: x koordinat; 1 Bit indeks: koordinat y; 2 Bit indeks: cHessInfo = {"-1", "-1", "0"}; int i = 0; // bendera bit string chessInfotoken; while (usermsgtoken.hasmoretokens ()) {chessInfotoken = (string) usermsgtoken.nextToken (""); if (i> = 1 && i <= 3) {chessInfo [i - 1] = chessInfotoken; } i ++; } Currpad.PaintNetFirPoint (integer.parseint (chiSinfo [0]), integer .parseint (chiSinfo [1]), integer.parseint (cHessInfo [2])); } lain if (msgrreCeived.startswith ("/youName")) {// pesan yang diterima diganti namanya menjadi currpad.chessselfname = msgreceived.substring (10); } lain jika (msgrreCeived.equals ("/error")) {// pesan kesalahan yang diterima adalah currpad.statustext.setText ("Pengguna tidak ada, silakan bergabung kembali!"); }} // Kirim pesan public void sendMessage (string sndmessage) {coba {currpad.outputData.writeutf (sndmessage); } catch (Exception ea) {ea.printstacktrace () ;; }} public void run () {string msgreReived = ""; coba {while (true) {// tunggu input informasi msGrreved = Currpad.inputData.readutf (); dealwithmsg (msgreceived); }} catch (ioException es) {}}} Mulailah mengembangkan modul server di bawah ini
1. Kembangkan Panel Informasi Server
impor java.awt.borderlayout; impor java.awt.color; impor java.awt.flowlayout; impor java.awt.label; impor java.awt.panel; impor java.awt.textarea; impor javax.swing.jlabel; /*** Dibuat oleh Administrator pada 2016/11/21. */ kelas publik servermsgpanel memperluas panel {public textarea msgtextArea = new TextArea ("", 22, 50, TextArea.scrollbars_vertical_only); Public Jlabel StatusLabel = New Jlabel ("Koneksi Saat Ini:", Label.Left); panel publik msgpanel = panel baru (); Status Panel Publik = Panel Baru (); Public ServermSgPanel () {setsize (350, 300); Securbackground (color.light_gray); setLayout (borderlayout baru ()); msgpanel.setLayout (flowlayout baru ()); msgpanel.setsize (210, 210); statuspanel.setLayout (borderlayout baru ()); statusPanel.setsize (210, 50); msgpanel.add (msgtextArea); StatusPanel.Add (StatusLabel, BorderLayout.west); add (msgpanel, borderlayout.center); Tambah (StatusPanel, BorderLayout.North); }} 2. Kembangkan proses server
impor java.io.datainputstream; impor java.io.dataoutputStream; impor java.io.ioException; impor java.net.socket; impor java.util.enumeration; impor java.util.hashtable; impor java.util.stringtokenizer; /*** Dibuat oleh Administrator pada 2016/11/21. */ kelas publik FirServerThread memperluas Thread {Socket ClientCocket; // simpan informasi soket klien hashtable clientdataHash; // Simpan hash hashtable clientNameHash yang sesuai dengan port klien dan aliran output; // Simpan hash hashtable chesspeerbash yang sesuai dengan soket klien dan nama klien; // Simpan hash servermsgpanel yang sesuai dengan pencipta game dan goiner goiner; boolean isClientclosed = false; FirServerThread publik (Socket ClientSocket, Hashtable ClientDataHash, Hashtable ClientNameHash, Hashtable ChesspeerHash, Server ServererGPanel) {this.clientsocket = ClientSocket; this.clientDataHash = clientDataHash; this.clientNameHash = clientNameHash; this.chesspeerbash = cyspeerbash; this.servermsgpanel = server; } public void dealwithmsg (string msgreReved) {string clientName; String peername; if (msgrreVeived.startswith ("/")) {if (msgreReived.equals ("/list")) {// Informasi yang diterima adalah untuk memperbarui umpan balik daftar pengguna (getUserList ()); } lain if (msgreReived.startswith ("/creatgame [inchess]")) {// pesan yang diterima adalah untuk membuat gim gamecreAnterame = msgreceived.substring (20); // Dapatkan nama server yang disinkronkan (clientNameHash) {// Masukkan port pengguna di daftar pengguna clientNameHash.put (clientocket, msgreceived.substring (11)); } disinkronkan (ChesspeerHash) {// Setel host ke state tunggu cheSpeerhash.put (gamecreAnterame, "tunggu"); } Umpan balik ("/youName" + clientNameHash.get (ClientSocket)); sendgamepeermsg (gamecreantername, "/ok"); sendPublicMSG (getUserList ()); } lain if (msgrreCeived.startswith ("/joingame")) {// pesan yang diterima adalah saat bergabung dengan game stringTokenizer usertokens = new stringTokenizer (msgrreSeived, ""); 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; // Dapatkan kehidupan pemain} nameIndex ++; } gamecreatorname = playernames [0]; gamePaticIpantName = playernames [1]; if (chesspeerhash.containskey (gamecreatorname) && chesspeerhash.get (gamecreatorname) .equals ("tunggu")) {// game ini telah dibuat disinkronkan (clientNameHash) {// tambahkan clientNameHash.put.pute) yang sesuai ("inci]" } disinkronkan (ChesspeerHash) {// Tambahkan atau ubah chiSPeerhash.put yang sesuai (GameCreatorname, GamePaticIpantName); } sendPublicMSG (getUserList ()); // Kirim pesan ke game joiner sendgamepeermsg (gamePaticipantName, ("/peer" + "[inchess]" + gamecreatorname)); // Kirim game ke pembuat game Sendgamepeermsg (gamecreatorname, ("/peer" + "[inchess]" + gamePaticipantName)); } else {// Jika game tidak dibuat, game ditolak untuk ditambahkan sendgamepeermsg (gamePaticIpantName, "/reject"); coba {closeClient (); } catch (Exception ez) {ez.printstacktrace (); }}} lain if (msgrreved.startswith ("/[inchess]")) {// pesan yang diterima adalah int firstlocation = 0, lastlocation; lastlocation = msgreReived.indexOf ("", 0); peerName = msgreceived.substring ((firstlocation + 1), lastlocation); msgrreVeived = msgrreved.substring ((lastlocation + 1)); if (sendgamePeermsg (peername, msgrreaded)) {umpan balik ("/error"); }} lain jika (msgrreved.startswith ("/giving")) {// pesan yang diterima adalah ketika Anda menyerahkan gim string chessclientName = msgreceived.substring (8); if (chesspeerhash.containskey (chiSSclientName) &&! ((string) chesspeerhash.get (chiSclientName)) .equals ("tunggu")) {// pemenangnya adalah gim joiner, kirim pesan kemenangan sendgamepeerMsg (string) chesspeerHash.get (cesscressclie "(string) chesspeerHash.get (cresscressco (string); Sinkronisasi (ChessPeerHash) {// Hapus pengguna keluar dari game Chesspeerhash.remove (ChessClientName); }} if (chesspeerhash.containsValue (chiSSclientName)) {// pemenangnya adalah pencipta permainan dan mengirimkan pesan kemenangan sendgamepeermsg ((string) gethashkey (cyspeerhash, cysclientname), "/youwin"); disinkronkan (ChesspeerHash) {// hapus pengguna keluar dari game chesspeerhash.remove ((string) gethashkey (chesspeerhash, chessclientName)); }}} else {// Ketika informasi yang diterima adalah informasi lain int lastlocation = msgrread.indexof ("", 0); if (lastlocation == -1) {umpan balik ("perintah tidak valid"); kembali; }}} else {msgreReived = clientNameHash.get (clientocket) + ">" + msgrreSeived; servermsgpanel.msgtextarea.append (msgreceived + "/n"); sendPublicMSG (msgreSeived); servermsgpanel.msgtextarea.setCaretposition (servermsgpanel.msgtextarea.getText () .length ()); }} // Kirim public void sendPublicMSg (string publicmsg) {disinkronkan (clientDataHash) {for (enumeration enu = clientDataHash.elements (); enu .hasmoreElements ();) {dataOutputStream outputData = (dataOutputStream) (); coba {outputData.writeutf (publicmsg); } catch (ioException ES) {es.printstacktrace (); }}}}} // Kirim informasi kepada pengguna dalam game yang ditentukan public boolean sendgamepeermsg (string gamepeertarget, string gamepeermsg) {for (enumeration enu = clientDataHash.keys (); enu. enu.nextelement (); if (gamePeerTarget.equals ((string) clientNameHash.get (userclient)) &&! gamepeerTarget.equals ((string) clientNameHash .get (clientocket))) {// disinkronkan (clientDataHash) {// Buat output stream output DataOutputStream peeroutDataCa = (clientDataHash) { / 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 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.开发服务器端
impor java.io.*; import java.net.*; import java.awt.*; impor 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); } }); mengemas(); setVisible(true); setSize(400, 300); setResizable(false); mengesahkan(); 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.*; impor java.io.*; import java.net.*; impor 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); mengemas(); 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; Kembali Benar; } 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){} } }至此,网络版五子棋就算是开发完成了。关于这么多类和包的关系如下图:
Di atas adalah semua konten artikel ini. Saya berharap ini akan membantu untuk pembelajaran semua orang dan saya harap semua orang akan lebih mendukung wulin.com.