Dieser Artikel teilt den spezifischen Code für die Java -Implementierung Goziqi Online -Version für Ihre Referenz. Der spezifische Inhalt ist wie folgt
Anforderungsanalyse:
Für Online -Goji müssen die folgenden Funktionen basierend auf dem normalen Goji hinzugefügt werden:
1. Haben Sie eine Serverseite und einen Client. Nachdem sich Benutzer über den Client beim Server angemeldet haben, können sie Spiele mit anderen angemeldeten Benutzern spielen.
2. Der Server unterstützt mehrere Benutzergruppen, um gleichzeitig Spiele zu spielen
3. Benutzer können neue Spiele auf dem Server erstellen oder erstellte Spiele beitreten
4. Benutzer können sich unterhalten und kommunizieren, während sie Schach spielen
Aus den oben genannten Erkenntnissen können wir die Funktionen kennen, die implementiert werden müssen:
・ Bereitstellung von Server- und Clientfunktionen
・ Der Server überwacht den Anmeldestatus des Clients und erlaubt mehrere Clients, sich anzumelden
・ Benutzer können sich über den Client beim Server anmelden und dann sehen sie andere Benutzer des Servers derzeit online und chatten mit ihm usw.
・ Nach dem Anmeldung auf dem Server können Benutzer ein neues Gozi -Spiel erstellen oder sich dem erstellten Gozi -Spiel anschließen.
・ Benutzer können Spiele mit anderen Benutzern wie gewöhnlichem Goji über den Kunden spielen
Gemäß der Funktion ist das Netzwerk Gochi in 4 Module unterteilt: nämlich das User Panel -Modul, das Board -Panel -Modul, das Gochi -Servermodul und das Gochi -Client -Modul
Lassen Sie uns das Benutzerpanel -Modul kompilieren:
1. Entwickeln Sie das Benutzerlistenfeld
import Java.awt.*; /*** Erstellt vom Administrator am 2016/11/21. */// Im Ausgangszustand werden 10 Informationen mit dem Namen "No User" zur Liste hinzugefügt, was angibt, dass der Server gleichzeitig bis zu 10 Benutzer online unterstützt. public userListPad () {setLayout (new BorderLayout ()); für (int i = 0; i <10; i ++) {userList.add (i+"."+"no user"); } add (userList, borderLayout.Center); }} 2. Entwickeln Sie das Benutzer -Chat -Panel
Javax.swing importieren.*; import Java.awt.*; /*** Erstellt vom Administrator am 2016/11/21. */// Das Chat -Bereich ist eine Textregalea -Ansichtskontrolle mit einer vertikalen Bildlaufleiste. // Der Textbereich wird dem Panel unter Verwendung des Layout -Formats "BorderLayout" hinzugefügt. public class userChatpad erweitert jpanel {public jtextArea chatTextarea = new JtextArea ("Befehlsbereich", 18,20); public userChatpad () {setLayout (new BorderLayout ()); chattextarea.setAutoscrolls (true); chattextarea.setlinewrap (true); add (chattextarea, borderLayout.Center); }} 3. Entwickeln Sie das Benutzereingangsbereich
Javax.swing importieren.*; import Java.awt.*; /*** Erstellt vom Administrator am 2016/11/21. */// Das Panel enthält zwei Ansichtssteuerelemente // contentInePt ist ein Textfield -Steuerelement, in dem Benutzer Chat -Informationen eingeben können. public jcomBobox userChoice = new jcomBobox (); public userInputPad () {setLayout (neuer FlowLayout (FlowLayout.Left)); für (int i = 0; i <50; i ++) {userChoice.additem (i+"."+"no user"); } userChoice.setSize (60,24); add (userChoice); add (contentInputted); }} 4. Entwickeln
Javax.swing importieren.*; import Java.awt.*; /*** Erstellt vom Administrator am 2016/11/21. */ Public Class UserControlpad erweitert JPanel {public JLabel iPlabel = new Jlabel ("IP", jlabel.left); public JTextField ipInputted = new JTextField ("localhost", 10); Public Jbutton Connectbutton = New Jbutton ("Connect to Server"); Public Jbutton CreateButton = New Jbutton ("Create Game"); Public Jbutton Joinbutton = New Jbutton ("Join Game"); Public Jbutton CancelButton = New Jbutton ("Give Up Game"); Public Jbutton ExitButton = New Jbutton ("Exit Game"); public UserControlpad () {setLayout (neuer FlowLayout (FlowLayout.Left)); SetBackground (color.light_gray); add (iplabel); add (ipinputiert); add (ConnectButton); add (createButton); add (joinbutton); add (AbbrechenButton); add (exitbutton); }} Beginnen Sie unten mit der Entwicklung des Board -Panel -Moduls
1. Entwickeln Sie schwarzes Schach
import Java.awt.*; /*** Erstellt vom Administrator am 2016/11/21. */ public class firpointBlack erweitert Canvas {Firpad Padbelonged; // das Board, zu dem das schwarze Schach öffentlich firPointblack (Firpad Padbelonged) {setSize (20, 20); // Setzen Sie die Schachstücksgröße this.padbelonged = padbelonged; } public void Paint (Grafik g) {// Schachstück zeichnen G.SetColor (color.black); G.Filloval (0, 0, 14, 14); }} 2. Kategorie weißer Schach entwickeln
import Java.awt.*; /*** Erstellt vom Administrator am 2016/11/21. */ public class firpointwhite erweitert Canvas {Firpad Padbelonged; // das Board, zu dem das weiße Schach öffentlich firpointwhite gehört (Firpad Padbelonged) {setSize (20, 20); this.padbelonged = padbelonged; } public void Paint (Grafik g) {// Schachstücke zeichnen G.SetColor (color.white); G.Filloval (0, 0, 14, 14); }} 3. Entwickeln Sie ein Schachbretttafel
import Java.awt.*; import Java.awt.event.*; import Java.io.*; Java.net importieren.*; importieren javax.swing.jtextfield; /*** Erstellt vom Administrator am 2016/11/21. */ public class Firpad erweitert das Panel implementiert Mouselistener, actionListener {// Kann die Maus verwendet werden. // ob man öffentlich boolean gewinnt iswinned = false; // Ob Schach öffentlich boolean isgaming = false; // x -achse Koordinatenbits des Schachstücks Public int chessx_pos = -1; // y -achse -Koordinatenbits des Schachstücks Public int chessy_pos = -1; // Farbe des Schachstücks öffentlich int chesscolor = 1; // schwarze X-Axis-Koordinaten-Bit-Array Public int chessblack_xpos [] = new int [200]; // schwarze y-achse-Koordinaten-Bit-Array Public int chessblack_ypos [] = new int [200]; // White y-Achse-Koordinate Bit Array Public int chesswhite_xpos [] = new int [200]; // weißes Schach y-axis-Koordinaten-Ziffernarray Public int chesswhite_ypos [] = new int [200]; // Anzahl des schwarzen Schaches öffentlich int SchachblackCount = 0; // Anzahl des weißen Schaches Public int chesswhiteCount = 0; // Anzahl von schwarzem Schach gewinnt öffentliche int chessblackvictimes = 0; // Anzahl des weißen Schaches gewinnt das öffentliche int chesswhitevictimes = 0; // Anzahl des weißen Schaches gewinnt das öffentliche int chesswhitevictimes = 0; // Ärmelnschnittstellen öffentliches Sockelschachkind; public DataNputStream InputData; public DataOutputStream outputData; public String chesselfName = null; public String chesspeername = null; public String host = null; public int port = 4331; public textField Statusext = neues Textfeld ("Bitte verbinden Sie eine Verbindung zum Server!"); öffentliches Firthread Firthread = New Firthread (this); public Firpad () {setSize (440, 440); setLayout (null); SetBackground (color.light_gray); addmouselistener (dies); add (StatuStext); StatuseText.SetBounds (neues Rechteck (40, 5, 360, 24)); StatuseText.Seetedable (falsch); } // Verbindung zum Host Public Boolean ConnectServer (String Serverip, Int Serverport) löst eine Ausnahme aus {try {// Erhalten Sie den Host -Port chessSocket = new Socket (Serverip, Serverport); // Erhalten Sie den Eingabestream inputData = new DataNputStream (chessSocket.getInputStream ()); // OutputData = new DataOutputStream (chessSocket.getOutputStream ()); Firthread.Start (); zurückkehren; } catch (ioException ex) {statUntext.setText ("Verbindung fehlgeschlagen! /n"); } return false; } // Setzen Sie den Board -Status beim Gewinnen öffentlicher void setvicstatus (int vicchesscolor) {// das Board this.removeall (); // Setzen Sie die schwarze Schachposition auf Null für (int i = 0; i <= chessblackCount; i ++) {chessblack_xpos [i] = 0; CHESSBLACK_YPOS [i] = 0; } // Setzen Sie die Position des weißen Schachs auf Null für (int i = 0; i <= chesswhiteCount; i ++) {chesswhite_xpos [i] = 0; chesswhite_ypos [i] = 0; } // Die Anzahl des schwarzen Schaches auf dem Brettschachcount = 0 löschen; // Die Anzahl des weißen Schaches auf dem BrettschachschichthiteCount = 0 löschen; add (StatuStext); StatuseText.SetBounds (40, 5, 360, 24); if (vicchesscolor == 1) {// schwarzes Schach gewinnt Schachblackvictimes ++; statUntext.setText ("schwarz, schwarz: weiß" + schachblackvictimes + ":" + chesswhiteVictimes + ", Spiel -Neustart, Warte auf Weiß ..."); } else if (vicchesscolor == -1) {// weißes Schach gewinnt SchachhiteVictimes ++; statUntext.setText ("schwarz: weiß" + schachblackvictimes + ":" + chesswhiteVictimes + ", Spiel -Neustart, Warte auf Schwarz ..."); }} // Erhalten Sie die Position des angegebenen Schachstücks public void setLocation (int xpos, int ypos, int chesscolor) {if (chesscolor == 1) {// Wenn das Schachstück schwarz ist, chessblack_xpos [chessblackCount] = xpos * 20; CHESSBLACK_YPOS [CHESBLACKCOUNT] = yPOS * 20; SchachblackCount ++; } else if (chesscolor == -1) {// Wenn das Schachstück weiß ist, chesswhite_xpos [chesswhiteCount] = xpos * 20; Schachhitzer ++; }} // Bestimmen Sie, ob der aktuelle Status ein publikanischer booleaner Checkvicstatus (int xpos, int ypos, int chesscolor) {int chessLinkedCount = 1 ist; // Anzahl der vernetzten Schachkompetenzkompare = 1; // wurde verwendet, um zu vergleichen, ob Sie weiterhin ein Stück intschessocompareIndex = 0 durchqueren möchten; // die Indexposition des Stücks, das in Closegrid = 1 verglichen werden soll; // Die Position des benachbarten Gitters if (chesscolor == 1) {// Schachkessel = 1; // Wenn das Schachstück selbst gezählt wird, ist die anfängliche Anzahl der Verbindungen 1 // jedes Paar für Loop -Anweisungen unten ist eine Gruppe, da die Position der nächsten Periode eher in der Mitte sein kann als an beiden Enden für (CloseGrid = 1; CloseGrid <= 4; CloseGrid ++) {// transpatieren Sie 4 adjacent -grids (chesstocompareIndex = 0; chesstocentx; Chesstocompareindex ++) {// durch alle schwarzen Schachstücke auf der Tafel transpat ((xpos+closeGrid) * 20 == CHESSBLACK_XPOS [CHESTOCOMPAREDEX]) && ((ypos * 20) == CHESSBLACK_YPOS [CHESSCOMPARIDEX]))))) {// // // // // // // // // // // concessblack_ypos [schusstocompos. = Schachkessel + 1; // 1 zu der Anzahl der Verbindungen hinzufügen, wenn (Schachkessel == 5) {// Wenn die fünf Teile verbunden sind, gibt der Sieg wahr zurück; }}}} if (chessLinkedCount == (schachkompare+1)) {chessLinkedCompare ++; } else {// Wenn es in der Mitte ein Schachstück gibt, das nicht schwarz ist, wird es in diesen Zweig gelangen, und es besteht keine Notwendigkeit, zu diesem Zeitpunkt erneut zu brechen. } } for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if (((xPos - closeGrid) * 20 == chessBlack_XPOS[chessToCompareIndex]) && (yPos * 20 == CHESSBLACK_YPOS [CHESTOCOMPAREDEX])) {// Bestimmen Sie, ob die vier Schachstücke links von der derzeit spielenden Schachkessel ++; if (chessLinkedCount == 5) {return true; }}}} if (chessLinkedCount == (schachkompare+1)) {chessLinkedCompare ++; } else {break; }} // beim Eingeben eines neuen Satzes von für Schleifen, die Anzahl der Verbindungen zurücksetzen usw. Schachkessel = 1; Schachkompetenz = 1; für (closeGrid = 1; closeGrid <= 4; closeGrid ++) {für (chestocompareindex = 0; chesstocompardex <= schalteblackCount; chestocompareindex+) {if ((xpos * 20 == chessblack_xpos CHESSBLACK_YPOS [CHESTOCOMPAREDEX])) {// Bestimmen Sie, ob die oberen 4 Teile des aktuell spielenden Schachkessel ++; if (chessLinkedCount == 5) {return true; }}} if (chessLinkedCount == (schachkompare+1)) {schachkompare ++; } else {break; }} für (closeGrid = 1; closeGrid <= 4; closeGrid ++) {für (chesstocompareindex = 0; chesstocompareindex <= schalteblackCount; chesstocompareIndex ++) {if ((XPOS * 20 == CHESSBLACK_XPOS [CHESSTOCPOS)) {if (xpos * 20 == chessblack_xpos [chesstocompos)). CHESSBLACK_YPOS [CHESTOCOMPAREDEX])) {// Bestimmen Sie, ob die vier Teile unter dem derzeit gespielten Schachkessel ++ gespielt wurden; if (chessLinkedCount == 5) {return true; }}} if (chessLinkedCount == (schachkompare+1)) {schachkompare ++; } else {break; }} chessLinkedCount = 1; Schachkompetenz = 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 [CHESSTOCOMPAREDEX]) {// Bestimmen Sie, ob die vier Schachsteine in der oberen linken Richtung des aktuellen Schachkesselns ++; } } for (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if (((xPos + closeGrid) * 20 == chessBlack_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * 20 == CHESSBLACK_YPOS [CHESSTOCOMPAREDEX]) {// Bestimmen Sie, ob die vier Schachteile in der unteren rechten Richtung des aktuellen Schachstücks schwarzer Schachkessel sind; } else {break; CHESSBLACK_XPOS [CHESSTOCOMPAREDEX]) && (ypos+closeGrid) * 20 == CHESSBLACK_YPOS [CHESSTOCOMDEX]) {// Bestimmen Sie, ob die vier Schachstücke in der oberen rechten Richtung des aktuellen Chess -Stücks schwarzen Chesslink -}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} (Schachspannung == (Schachkompetenz+1) {Schachkompetenz ++;} else {break; () Return true; . der aktuell Schachspitze ++; . der aktuell Schachkasse ++; <=4; CHESSWHITE_YPOS [CHESSTOCOMPAREDEX]) {// TOP 4 -Teile des aktuellen Spiels von Schachsteinen {return true; (closeGrid = 1; closeGrid <= 4; closeGrid++) { for (chessToCompareIndex = 0; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if ((xPos * 20 == chessWhite_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * 20 == CHESSWHITE_YPOS [CHESSTOCOMDEX]) {// bestimmen, ob die vier Teile unter dem derzeitigen Schachkessel ++ gespielt haben; Schachkessel = 1; CHESSWHITE_XPOS [CHESSTOCOMPAREDEX]) && (ypos+closeGrid) * 20 == CHESSWHITE_YPOS [CHESSTOCOMDEX]) {// Bestimmen Sie, ob alle 4 Teile in der oberen linken Richtung des aktuellen Chess -Stücks weiße Chesslinkedcount+}}}}}} ash; (Schachkasse == (Schachkompetenz+1) {Schachkompetenz ++;} else {break; () Return true; chesstocompareIndex <= chesswhiteCount; Schachstück sind weiße Schachkunst ++; . Die vier Teile in der linken Seite des aktueller Schachkessel ++; Paint (Grafik g) {für (int i = 40; i <= 380; i = i + 20) {G.Drawline (40, i, 400, i); 400, 400); // chesspawn public void Paintfirpoint (int xpos, int ypos, int chesscolor) {firpointblack firPblack = new FirpointBlack (this); Chesscolor); // Schachteile fügen Sie dem Board FIRPBLACK. sonst {// status firthead.sendMessage (" /" + chesspeername + " /schach" + xpos + "ypos +" " + chesscolor); Parameter als schwarzer Schach Sieg ismouseenabled = false; firthead.sendMessage (" /" + chesspeername + " /schach" + xpos + "" + ypos + "" + chesscolor); XPOS + " + ypos +", es ist schwarz. "); 7, 16); setLocation (xpos, ypos, chesscolor); statustext.setText ("schwarz" + schachcrackCount + "step)" + xpos + "" + ypos + ", es ist der weiße Quadrat."); 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) {// Es wird keine Aktion durchgeführt, wenn die Schachposition falsch ist} else {PaintFirpoint (A, B, Chesscolor); void mouseclicked (mouseevent e) {} public void actionPerformed (actionEvent e) {}} 4. Entwickeln Sie Schachbrettfäden
Import Java.util.Stringtokenizer; importieren java.io.ioException; /*** Erstellt vom Administrator am 2016/11/21. */ Public Class Firthread erweitert Thread {Firpad Currpad; // Das Schachausschuss des aktuellen Threads öffentlich firThread (firpad currpad) {this.currpad = currpad; } // Verarbeiten Sie die erhaltenen Informationen public void DealWithsg (String msgreceived) {if (msgreceived.startswith ("/schess") {// Die empfangenen Informationen sind SchachstringTokenizer Usermsgtoken = new StringOkenizer (msgreceived, ""); // Die Auswahl an Schachstückeninformationen und 0 Indizes lautet: X -Koordinate; 1 Indexbit: Y -Koordinate; 2 Indexbit: chessinfo = {"-1", "-1", "0"}; int i = 0; // Bit String Chessinfotoken; while (usermsgtoken.hasmoretokens ()) {chessinfotoken = (String) usermsgtoken.NextToken (""); if (i> = 1 && i <= 3) {chessinfo [i - 1] = chessinfotoken; } i ++; } currpad.paintNetFirpoint (Integer.ParseInt (chessinfo [0]), Integer .ParseInt (chessinfo [1]), Integer.ParseInt (chessinfo [2])); } else if (msgreceived.startsWith ("/yourname")) {// Die empfangene Nachricht wird umbenannt.ChessSelfname = msgreceived.substring (10); } else if (msgreceived.equals ("/error")) {// Die empfangene Fehlermeldung ist CurrPad.StatUntext.setText ("Der Benutzer existiert nicht, bitte wieder anjoin!"); }} // Senden Sie die Nachricht public void sendMessage (String sndMessage) {try {currpad.outputData.WriteuTf (SNDMessage); } catch (Ausnahme EA) {ea.printstacktrace () ;; }} public void run () {string msgreced = ""; Versuchen Sie {while (true) {// Warten Sie auf Informationen eingeben msgreced = currpad.inputData.readutf (); DealWithmsg (msGreceived); }} catch (ioException es) {}}} Entwickeln Sie das unten stehende Servermodul
1. Entwickeln Sie Serverinformationsbereich
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; /*** Erstellt vom Administrator am 2016/11/21. */ public class servermsgpanel erweitert das Panel {public textarea msgTextArea = new textAreaaa ("", 22, 50, textArea.scrollBars_vertical_only); public JLabel statusLabel = new JLabel ("Aktuelle Verbindungen:", label.left); öffentliches Panel msgpanel = neues Panel (); öffentliches Panel statusPanel = new panel (); public servermsgpanel () {setSize (350, 300); SetBackground (color.light_gray); setLayout (neuer BorderLayout ()); msgpanel.setLayout (neuer FlowLayout ()); msgpanel.setsize (210, 210); statusPanel.setLayout (neuer BorderLayout ()); statuspanel.setsize (210, 50); msgpanel.add (msGtextArea); statusPanel.add (StatusLabel, BorderLayout.West); add (msgpanel, borderLayout.Center); add (statuspanel, borderLayout.north); }} 2. Entwickeln Sie den Serverprozess
importieren java.io.datainputstream; importieren java.io.dataoutputStream; importieren java.io.ioException; importieren java.net.socket; Import Java.util.Enumeration; import Java.util.hashtable; Import Java.util.Stringtokenizer; /*** Erstellt vom Administrator am 2016/11/21. */ Public Class Firerverthread erweitert Thread {Socket ClientSocket; // Client Socket Information Hashtable ClientDatahash; // Speichern Sie den Hash -Hashtable clientnamehash, der dem Client -Port und dem Ausgabestream entspricht. // Speichern Sie den Hash -Hashtable -Chesspeerhash, der dem Client -Socket und dem Clientnamen entspricht. // Speichern Sie das Hash -Servermsgpanel, der dem Spielersteller und dem Game -Joiner entspricht. boolean isclientcLosed = false; public Firerverthread (Socket ClientSocket, Hashtable ClientDatahash, Hashtable ClientNamehash, Hashtable chespeerhash, Servermsgpanel Server) {this.clientsocket = clientocket; this.clientDatahash = ClientDatahash; this.clientnamehash = clientnamehash; this.chespeerhash = chespeerhash; this.servermsgpanel = server; } public void DealWithsg (String msGreced) {String clientName; String Peername; if (msgreceived.startswith ("/")) {if (msgreceived.equals ("/list") {// Die empfangenen Informationen sollen das Feedback der Benutzerliste aktualisieren (getUserList ()); } else if (msgreceived.StartsWith ("/creatGame [Inchess]")) {// Die empfangene Nachricht soll den Game String Gamecreatername = msgreceived.substring (20) erstellen; // den Servernamen synchronisiert (clientNamehash) {// den Benutzerport in die Benutzerliste clientnamehash.put (Clientocket, msgreceived.substring (11)) einfügen; } synchronized (chespeerhash) {// Setzen Sie den Host auf den Wartezustand chespeerhash.put (Gamecreatername, "Wait"); } Feedback ("/yourName" + ClientNamehash.get (ClientSocket)); sendgamepeermsg (Gamecreatername, "/ok"); sendPublicmsg (getUserList ()); } else if (msgreceived.StartsWith ("/Joingame")) {// Die empfangene Nachricht ist beim Beitritt zum Spiel StringTokenizer usertokens = new StringTokenizer (msgreceived, ""); String UserToken; String GamecreatorName; String GamepaticipantName; String [] Playernames = {"0", "0"}; int nameIndex = 0; while (usertokens.hasmoretokens ()) {UserToken = (String) UserStokens.NextToken (""); if (nameIndex> = 1 && nameIndex <= 2) {Playernames [nameIndex - 1] = UserSertoken; // Erhalten Sie das Leben des Spielers} nameIndex ++; } gamecreatorname = Playernames [0]; GamepaticipantName = Playernames [1]; if (chespeerhash.containSkey (GamecreatorName) && chespeerhash.get (GamecreatorName) .Equals ("Wait")) {// Das Spiel wurde synchronisiert (ClientNamehash) {// addiere die entsprechenden Clientnamehash.put (Clientsocket, ("[Inchess]" + gamepaticiPatripaticiPated). } synchronisiert (chespeerhash) {// addieren oder modifizieren Sie den entsprechenden Chespeerhash.put (GameCreatorName, GamepaticipantName); } sendPublicmsg (getUserList ()); // Nachricht an den Game -Joiner SendgamePeerMSG (GamepaticipantName, ("/Peer" + "[Inchess]" + Gamecreatorname)); // Sende das Spiel an den Game Creator Sendgamepeermsg (GamecreatorName, ("/Peer" + "[Inchess]" + GamepaticipantName)); } else {// Wenn das Spiel nicht erstellt wird, wird das Spiel geweigert, Sendgamepeermsg (GamepaticipantName, "/Reject") hinzugefügt zu werden. try {Closeclient (); } catch (Ausnahme ez) {ez.printstacktrace (); }}} else if (msgreceived.startswith ("/[Inchess]")) {// Die empfangene Nachricht ist int firstLocation = 0, lastLocation; lastLocation = msgreceived.indexof ("", 0); pername = msgreceived.substring ((FirstLocation + 1), LastLocation); msgreceived = msgreceived.substring ((lastLocation + 1)); if (sendgamepeermsg (peername, msgreceived)) {feedback ("/error"); }} else if (msgreceived.startswith ("/giveup") {// Die empfangene Nachricht ist, wenn Sie das Spiel String Chessclientname = msgreceived.substring (8) aufgeben; if (chespeerhash.containSkey (chessclientname) &&! ((String) chespeerhash.get (chessclientname)) .equals ("warte")) {// Der Gewinner ist der Spiel -Joiner, senden Sie die Siegesnachricht Sendgamepeermsg ((String). synchronisiert (chespeerhash) {// Der Benutzer löschen Sie das Spiel chespeerhash.remove (chessclientname); }} if (chespeerhash.containsValue (chessclientname)) {// Der Gewinner ist der Spielersteller und sendet die Victory -Nachricht sendgamepeermsg ((String) Gethashkey (Chespeerhash, Chessclientname), "/youwin"); Synchronized (chespeerhash) {// den Benutzer löschen Sie das Spiel chespeerhash.remove ((String) Gethashkey (chespeerhash, chessclientname)); }}} else {// Wenn die empfangenen Informationen weitere Informationen sind, int lastLocation = msgreceived.indexof ("", 0); if (lastLocation == -1) {feedback ("Ungültiger Befehl"); zurückkehren; }}} else {msgreceived = clientnamehash.get (ClientSocket) + ">" + msgreceived; servermsgpanel.msGtextArea.Append (msgreceived + "/n"); sendPublicmsg (msgreceived); servermsgpanel.msgTextarea.setCaretPosition (servermsgpanel.msGtextarea.getText () .Length ()); }} // public void sendPublicmsg (string publicmsg) {synchronized (clientDatahash) {für (Enumeration enu = clientDatahash.elements (); enu .hasmoreElements ();) {DataOutputStream -Ausgabedata = (DataOutputStream) Enu.Nextelement (); try {outputData.WriteUtf (PublicMSG); } catch (ioException es) {es.printstacktrace (); }}}}} // Informationen an den Benutzer im angegebenen Spiel public boolean sendgamepeermsg (String gamePeertarget, String Gamepeermsg) {für (Enumeration enu = clientDatahash.keys (); Enu.hasmoreelements (); enu.nextElement (); if (GamePeertarget.equals ((String) clientnamehash.get (userClient)) &&! Versuchen Sie {// Informationen senden 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.开发服务器端
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); } }); Pack(); setVisible(true); setSize(400, 300); setResizable(false); bestätigen(); try { createServer(4331, serverMsgPanel); } catch (Ausnahme 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.*; importieren 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); Pack(); 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; zurückkehren; } 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.开发客户端线程
importieren 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 ")) { // If the information obtained is the user list StringTokenizer userToken = new StringTokenizer(msgReceived, " "); int userNumber = 0; // Clear the client user list firClient.userListPad.userList.removeAll(); // Clear the client user drop-down box firClient.userInputPad.userChoice.removeAll(); // Clear the client user drop-down box firClient.userInputPad.userChoice.removeAll(); // Add an option to the client user drop-down box firClient.userInputPad.userChoice.addItem("all users"); while (userToken.hasMoreTokens()) { // When data exists in the received user information list String user = (String) userToken.nextToken(" "); // Get user information if (userNumber > 0 && !user.startsWith("[inchess]")) { // When user information is valid, firClient.userListPad.userList.add(user); // Add user information to the user list firClient.userInputPad.userChoice.addItem(user); // Add user information to the user drop-down box} userNumber++; } firClient.userInputPad.userChoice.setSelectedIndex(0);// The drop-down box selects everyone by default} else if (msgReceived.startsWith("/yourname ")) { // When the information received is the user's real name firClient.chessClientName = msgReceived.substring(10); // Get the user's real name firClient.setTitle("Java Goji Client" + "Username:" + firClient.chessClientName); // Set the title of the program Frame} else if (msgReceived.equals("/reject")) { // The message received is when the user is rejected try { firClient.firPad.statusText.setText("Cannot join the game!"); 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 ")) { // When receiving the message is waiting in the game, firClient.firPad.chessPeerName = msgReceived.substring(6); if (firClient.isCreator) { // If the user is the game builder firClient.firPad.chessColor = 1; // Set it to be black chess first firClient.firPad.isMouseEnabled = true; firClient.firPad.statusText.setText("Black..."); } else if (firClient.isParticipant) { // If the user is a game joiner firClient.firPad.chessColor = -1; // Set it as a white chess last sex firClient.firPad.statusText.setText("Game join, wait for the opponent."); } } else if (msgReceived.equals("/youwin")) { // The message received is victory information firClient.isOnChess = false; firClient.firPad.setVicStatus(firClient.firPad.chessColor); firClient.firPad.statusText.setText("opter exit"); firClient.firPad.isMouseEnabled = false; } else if (msgReceived.equals("/OK")) { // Received a message to create the game for successful firClient.firPad.statusText.setText("Game creation waiting for opponent"); } else if (msgReceived.equals("/error")) { // Received a message to firClient.userChatPad.chatTextArea.append("Error, exit the program./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 for chat information and enter wait state message = firClient.inputStream.readUTF(); dealWithMsg(message); } } catch (IOException es){} } }至此,网络版五子棋就算是开发完成了。关于这么多类和包的关系如下图:
Das obige ist der gesamte Inhalt dieses Artikels. Ich hoffe, es wird für das Lernen aller hilfreich sein und ich hoffe, jeder wird Wulin.com mehr unterstützen.