Cet article partage le code spécifique de la version en ligne de l'implémentation Java Goziqi pour votre référence. Le contenu spécifique est le suivant
Analyse des exigences:
Pour le goji en ligne, les fonctions suivantes doivent être ajoutées sur la base de Goji ordinaire:
1. Avoir un côté serveur et un client. Une fois que les utilisateurs se sont connectés au serveur via le client, ils peuvent jouer à des jeux avec d'autres utilisateurs connectés.
2. Le serveur prend en charge plusieurs groupes d'utilisateurs pour jouer à des jeux en même temps
3. Les utilisateurs peuvent créer de nouveaux jeux sur le serveur ou rejoindre des jeux créés
4. Les utilisateurs peuvent discuter et communiquer tout en jouant aux échecs
À partir de ce qui précède, nous pouvons connaître les fonctions qui doivent être implémentées:
・ Fournir des fonctions de serveur et client
・ Le serveur surveillera l'état de connexion du client et permettra à plusieurs clients de se connecter
・ Les utilisateurs peuvent se connecter au serveur via le client, puis ils peuvent voir d'autres utilisateurs du serveur actuellement en ligne et discuter avec eux, etc.
・ Après s'être connecté au serveur, les utilisateurs peuvent créer un nouveau jeu Gozi ou rejoindre le jeu Gozi créé.
・ Les utilisateurs peuvent jouer à des jeux avec d'autres utilisateurs comme le goji ordinaire via le client
Selon la fonction, le réseau gochi est divisé en 4 modules: à savoir le module du panneau d'utilisateur, le module du panneau de carte, le module de serveur Gochi et le module client Gochi
Commençons à compiler le module du panneau utilisateur:
1. Développer le panneau de liste d'utilisateurs
import java.awt. *; / ** * Créé par l'administrateur sur 2016/11/21. * / // Dans l'état initial, 10 informations nommées "Aucun utilisateur" seront ajoutées à la liste, indiquant que le serveur prend en charge jusqu'à 10 utilisateurs en ligne en même temps.//La liste est ajouté au panneau, en utilisant la liste "BorderLayout" Public Class UserListPad étend le panneau {public list userList = new List (10); public userListPad () {setLayout (new BorderLayout ()); pour (int i = 0; i <10; i ++) {userList.add (i + "." + "No User"); } add (userList, borderLayout.Center); }} 2. Développer un panneau de chat utilisateur
importer javax.swing. *; import java.awt. *; / ** * Créé par l'administrateur sur 2016/11/21. * / // Le panneau de chat est un contrôle de vue TextArea avec une barre de défilement verticale. // La TextArea est ajoutée au panneau, en utilisant le format de mise en page "BorderLayout". classe publique UserChatpad étend JPanel {public jTextArea ChatTextArea = new JTextArea ("Command Area", 18,20); public userChatpad () {setLayout (new BorderLayout ()); ChatTextArea.setAutoScrolls (true); ChatTextArea.setlineWrap (true); Add (ChatTextArea, BorderLayout.Center); }} 3. Développer un panneau d'entrée utilisateur
importer javax.swing. *; import java.awt. *; / ** * Créé par l'administrateur sur 2016/11/21. * / // Le panneau contient deux contrôles de vue // ContentInpit est un contrôle TextField, où les utilisateurs peuvent entrer dans les informations de chat Classe publique UserInputPad étend JPanel {public jTextField ContentInTatted = new JTextField ("", 26); public jComboBox userChoice = new JComboBox (); public userInputPad () {setLayout (new FlowLayout (FlowLayout.Left)); pour (int i = 0; i <50; i ++) {userChoice.additem (i + "." + "No User"); } userChoice.setSize (60,24); ajouter (userChoice); ajouter (contenuInputted); }} 4. Développer un panneau de fonctionnement utilisateur
importer javax.swing. *; import java.awt. *; / ** * Créé par l'administrateur sur 2016/11/21. * / classe publique UserControlpad étend JPanel {public JLabel iplabel = new JLabel ("ip", jLabel.left); public jTextfield ipinputted = new JTextfield ("localhost", 10); public jbutton connectButton = new Jbutton ("Connexion au serveur"); 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 ("sortie de sortie"); public userControlPad () {setLayout (new FlowLayout (FlowLayout.Left)); SetBackground (Color.light_Gray); ajouter (iPLabel); Add (ipInputted); Add (connectButton); Add (CreateButton); ajouter (joinbutton); Add (CancelButton); ajouter (exitbutton); }} Commencez à développer le module du panneau de carte ci-dessous
1. Développer des échecs noirs
import java.awt. *; / ** * Créé par l'administrateur sur 2016/11/21. * / classe publique FirPointBlack étend Canvas {Firpad PadBelond; // la planche à laquelle les échecs noirs appartiennent à Public FirPointblack (Firpad PadbElonged) {setSize (20, 20); // Réglez la taille de la pièce d'échecs this.PadBelonged = PadBelonged; } public void peinture (graphiques g) {// dessiner la pièce d'échecs g.setColor (color.black); G.Filloval (0, 0, 14, 14); }} 2. Développer la catégorie d'échecs blancs
import java.awt. *; / ** * Créé par l'administrateur sur 2016/11/21. * / classe publique FirPointwhite étend Canvas {Firpad PadBelonged; // la planche à laquelle les échecs blancs appartiennent à Public FirPointwhite (Firpad PadbElonged) {setSize (20, 20); this.padbelonged = padbelonged; } public void peinture (graphiques g) {// dessiner des pièces d'échecs g.setColor (color.white); G.Filloval (0, 0, 14, 14); }} 3. Développer un panneau d'échecs
import java.awt. *; import java.awt.event. *; importer java.io. *; importer java.net. *; import javax.swing.jtextfield; / ** * Créé par l'administrateur sur 2016/11/21. * / classe publique Firpad Extend Pannel implémente MouseListener, ActionListener {// La souris peut être utilisée publique Boolean IsmouseEenabled = false; // s'il faut gagner public booléen iswinned = false; // s'il faut jouer aux échecs public booléen isgaming = false; // Bits de coordonnées de l'axe x de la pièce d'échecs public int chessx_pos = -1; // Les bits de coordonnées de l'axe des y-axes de la pièce d'échecs public int chessy_pos = -1; // Couleur de la pièce d'échecs public int ChessColor = 1; // Black X-axis Coordonne Bit Array public int ChessBlack_xpos [] = new int [200]; // Black Y-axis Coordonne Bit Array public int ChessBlack_YPOS [] = new int [200]; // Array Bit de coordonnées de l'axe y blanc public public int ChessWhite_xpos [] = new int [200]; // Array White Chess Y-axis COORDINATION DIGIT PUBLIC INT CESSWHITE_YPOS [] = NOUVEAU INT [200]; // Nombre d'échecs noirs publics int ChessBlackCount = 0; // Nombre d'échecs blancs public int ChessWhiteCount = 0; // Nombre d'échecs noirs gagne le public int ChessBlackVictimes = 0; // Nombre d'échecs blancs gagne le public int effectwhiteVictimes = 0; // Nombre d'échecs blancs gagne le public int effectwhiteVictimes = 0; // Interface de manche à douille publique ChessSocket; Public DatainputStream InputData; Public DataOutputStream OutputData; public String CheselfName = null; public String ChessPeername = null; public String host = null; public int port = 4331; public TextField Statustext = new TextField ("Veuillez vous connecter au serveur!"); Public Firthread Firthread = New Firthread (this); public firpad () {setSize (440, 440); setLayout (null); SetBackground (Color.light_Gray); AddMouseListener (this); Add (StateStext); StatusText.SetBounds (nouveau rectangle (40, 5, 360, 24)); StateStext.setEdIT (false); } // Connexion à l'hôte public booléen connectServer (String ServerIp, int serverport) lève une exception {try {// obtenir le port hôte ChessSocket = new socket (serverIp, serverport); // obtient le flux d'entrée inputdata = new DatainputStream (ChessSocket.getInputStream ()); // obtient outputData = new DataOutputStream (ChessSocket.GetOutputStream ()); firthread.start (); Retour Vrai; } catch (ioException ex) {statusTExt.seTTExt ("Connexion a échoué! / n"); } return false; } // Définissez le statut du conseil d'administration lors de la victoire du public SetVicStatus (int vicChessColor) {// effacer le conseil d'administration.removeall (); // Définissez la position d'échecs noire sur zéro pour (int i = 0; i <= ChessBlackCount; i ++) {ChessBlack_xpos [i] = 0; ChessBlack_YPOS [i] = 0; } // Définissez la position des échecs blancs sur zéro pour (int i = 0; i <= ChessWhiteCount; i ++) {ChessWhite_xpos [i] = 0; ChessWhite_YPOS [i] = 0; } // effacer le nombre d'échecs noirs sur le tableau ChessBlackCount = 0; // effacer le nombre d'échecs blancs sur la planche ChessWhiteCount = 0; Add (StateStext); StateStext.setBounds (40, 5, 360, 24); if (vicChessColor == 1) {// Les échecs noirs gagnent ChessBlackVictimes ++; StateStext.SeTText ("noir, noir: blanc" + ChessBlackVictime + ":" + ChessWhitevicTimes + ", redémarrage du jeu, attendez le blanc ..."); } else if (vicChessColor == -1) {// Les échecs blancs gagnent ChessWhiteVictimes ++; StateStext.seTText ("Black: White" + ChessBlackVictimes + ":" + ChessWhiteVictimes + ", Game Redémarrer, attendre le noir ..."); }} // Obtenez la position de la pièce d'échecs spécifiée publique void setLocation (int xpos, int ypos, int chesscolor) {if (chesscolor == 1) {// Lorsque la pièce d'échec est noir, ChessBlack_xpos [ChessBlackCount] = xpos * 20; ChessBlack_YPOS [ChessBlackCount] = YPOS * 20; ChessBlackCount ++; } else if (ChessColor == -1) {// Lorsque la pièce d'échecs est blanche, ChessWhite_xpos [ChessWhiteCount] = xpos * 20; ChessWhiteCount ++; }} // Déterminez si l'état actuel est un état gagnant Boolean CheckVicStatus (int xpos, int ypos, int chesscolor) {int ChessLinkedCount = 1; // Nombre de ChessLinkedCompare connecté = 1; // Utilisé pour comparer si vous souhaitez continuer à traverser une pièce int chesstocompareIndex = 0; // La position d'index de la pièce à comparer int closegrid = 1; // la position de la grille adjacente if (ChessColor == 1) {// ChessLinkedCount = 1; // Si la pièce d'échecs elle-même est comptée, le nombre initial de connexions est 1 // chaque paire d'instructions pour la boucle ci-dessous est un groupe, car la position de la période suivante peut être au milieu plutôt qu'aux extrémités pour (Closegrid = 1; Closegrid <= 4; Closegrid ++) {// transpatation via 4 grilles adjacent pour (chessstocompareIndex = 0; chesstapareinde; ChesstoCompareIndex ++) {// Transipate à travers toutes les pièces d'échecs noires sur la planche if (((xpos + closegrid) * 20 == ChessBlack_Xpos [ChesstocompareIndex]) && ((ypos * 20) == ChessBlack_YPO = ChessLinkedCount + 1; // Ajouter 1 au nombre de connexions if (ChessLinkedCount == 5) {// Lorsque les cinq pièces sont connectées, la victoire renvoie True; }}}} if (ChessLinkedCount == (ChessLinkedCompare + 1)) {ChessLinkedCompare ++; } else {// S'il y a une pièce d'échecs au milieu qui n'est pas noire, il entrera dans cette branche, et il n'est pas nécessaire de traverser la rupture à ce moment; }} pour (closegrid = 1; closegrid <= 4; closegrid ++) {for (ChesstoCompareIndex = 0; ChesstoCompareIndex <= ChessBlackCount; ChesstoCompareIndex ++) {if ((xpos - closegrid) * 20 == 20 == = ChesstocompareIndeinde ChessBlack_YPOS [ChesstoCompareIndex])) {// Déterminez si les quatre pièces d'échecs à gauche de la lecture de ChessLinkedCount ++; if (ChessLinkedCount == 5) {return true; }}}} if (ChessLinkedCount == (ChessLinkedCompare + 1)) {ChessLinkedCompare ++; } else {break; }} // Lors de la saisie d'un nouvel ensemble de boucles pour les boucles, réinitialisez le nombre de connexions, etc. ChessLinkedCount = 1; ChessLinkedCompare = 1; pour (closegrid = 1; closegrid <= 4; closegrid ++) {for (ChesstoCompareIndex = 0; ChesstoCompareIndex <= ChessBlackCount; ChesstoCompareIndex ++) {if ((xpos * 20 == ChessBlack_xpos [ChesstocompareIndex]) && ((YPOS + Closegrid) * 20 == ChessBlack_YPOS [ChesstoCompareIndex])) {// Déterminez si les 4 premières pièces de la lecture de ChessLinkedCount ++ actuellement en jeu; if (ChessLinkedCount == 5) {return true; }}} if (ChessLinkedCount == (ChessLinkedCompare + 1)) {ChessLinkedCompare ++; } else {break; }} pour (closegrid = 1; closegrid <= 4; closegrid ++) {for (ChesstoCompareIndex = 0; ChesstoCompareIndex <= ChessBlackCount; ChesstoCompareIndex ++) {if ((xpos * 20 == ChessBlack_YPOS [ChesstoCompareIndex])) {// Déterminez si les quatre pièces en dessous du ChessLinkedCount ++ actuellement joué; if (ChessLinkedCount == 5) {return true; }}} if (ChessLinkedCount == (ChessLinkedCompare + 1)) {ChessLinkedCompare ++; } else {break; }} ChessLinkedCount = 1; ChessLinkedCompare = 1; pour (closegrid = 1; closegrid <= 4; closegrid ++) {pour (ChesstoCompareIndex = 0; ChesstoCompareIndex <= ChessBlackCount; ChesstoCompareIndex ++) {if (((xpos - closegrid) * 20 == {// déterminer si les quatre pièces de l'échec dans la direction supérieure gauche de la lecture de ChessLinkEdCount ++; }} pour (closegrid = 1; closegrid <= 4; closegrid ++) {for (ChesstoCompareIndex = 0; ChesstoCompareIndex <= ChessBlackCount; ChesstoCompareIndex ++) {if ((xpos + closegrid) * 20 == 20 == ChessBlack_YPOS [ChesstoCompareIndex])) {// Déterminez si les quatre pièces d'échecs dans la direction en bas à droite de la pièce d'échecs actuelle sont Black ChessLinkedCount ++; } else {Break;}} ChessLinkEdCount = 1; ChessLinkEdCompare = 1; ChessBlack_XPOS [ChesstoCompareIndex]) && (YPOS + Closegrid) * 20 == ChessBlack_YPOS [ChesstoCompareIndex]) {// Déterminez si les quatre pièces Chess dans la direction supérieure de la pièce d'échecs == 5) sont Black ChessLikedCount; (ChessLinkEdCount == (ChessLinkEdCompare + 1)) {ChessLinkEdCompare ++;} else {Break;}} pour (Closegrid = 1; ((XPOS - Closegrid) * 20 == ChessBlack_xpos [ChesstoCompareIndex]) && ((ypos - closegrid) * 20 == ChessBlack_YPOS [ChesstocompareIndex])) {// Déterminer si les quatre pièces Chess dans le bas de la direction de COURSCHED (ChessLiked sont Black CHESSLINKEDCOUNT; return true;}}} if (ChessLinkEdCount == (ChessLinkEdCompare + 1)) {ChessLinkEdCompare ++; (ChesstoCompareIndex = 0; ChesstoCompareIndex <= ChessWhiteCount; ChesstoCompareIndex ++) {if ((xpos + closegrid) * 20 == Chesswhite_xpos [ChesstocompareIndex]) && (ypos * 20 == Les quatre pièces [ChessStoPares de la lecture de ChessLinkEdCount ++; (ChesstoCompareIndex = 0; ChesstoCompareIndex <= ChessWhiteCount; ChesstoCompareIndex ++) {if ((xpos - closegrid) * 20 == Chesswhite_xpos [ChesstocompareIndex]) && (YPO de jouer à ChessLinkEdCount ++; <= 4; Closegrid ++) {pour (ChesstocompareIndex = 0; ChesstoCompareIndex <= ChessWhiteCount; ChesstoCompareIndex ++) {if ((xpos * 20 == ChessWhite_YPOS [ChesstoChyPareIndex]) {// Déterminez si les 4 premières pièces de la lecture de ChessLinkEdCount ++; (closegrid = 1; closegrid <= 4; closegrid ++) {for (ChesstoCompareIndex = 0; ChesstocompareIndex <= ChessWhiteCount; ChesstocompareIndex ++) {if ((xpos * 20 == ChessWhite_YPOS [ChesstoChyPareIndex]) {// Déterminez si les quatre pièces ci-dessous sont jouées par ChessLinkEdCount ++; ChessLinkEdCount = 1; ChessLinkEdCompare = 1; ChessWhite_XPOS [ChesstoCompareIndex]) && (YPOS + Closegrid) * 20 == ChessWhite_YPOS [ChesstoCompareIndex]) {// Déterminez si les 4 pièces dans la direction supérieure de la pièce d'échecs actuelle sont les White ChessLinkedCount ++; (ChessLinkEdCount == (ChessLinkedCompare + 1)) {ChessLinkEdCompare ++;} else {Break;}} pour (CloseGrid = 1; ((XPOS + Closegrid) * 20 == ChessWhite_xpos [ChesstoCompareIndex]) && ((ypos - clôture) * 20 == Chesswhite_YPOS [ChesstocompareIndex])) {// Déterminez les quatre pièces Chess dans la direction inférieure de la pièce COURSE COURSE COURT) return true;}} if (ChessLinkEdCount == (ChessLinkEdCompare + 1)) {ChessLinkEdCompare ++; ChesstocompareIndex ++) {if (((xpos + closegrid) * 20 == Chesswhite_xpos [ChesstocompareIndex]) && (ypos + closegrid) * 20 == Les pièces sont des échanges White ChessLinkEdCount ++; (ChesstoCompareIndex = 0; ChesstoCompareIndex <= ChessWhiteCount; ChesstoCompareIndex ++) {if ((xpos - closegrid) * 20 == Chesswhite_xpos [ChesstocompareIndex]) && (YPOS - CloseGrid) * 20 == Chesshite_YPOS] Les quatre pièces dans la direction inférieure de la plate-forme de la lecture de ChessLinkEdCought ++; peinture (graphiques g) {pour (int i = 40; i <= 380; i = i + 20) {g.Drawline (40, i, 400, i); 400, 400); // dessiner ChessPawn public void pentofrpoint (int xpos, int ypos, int chesscolor) {firpointblack firpblack = new firpointblack (this); Le statut de situation actuel estwinned = CheckVicStatus (XPOS), // Ajouter des pièces à l'échec à la planche firpblack.setbounds (xpos * 20 - 7, yPos * 20 - 7, 16, 16); Inconvénients} else {// Win Status Firthread.SendMessage ("/" + ChessPeername + "/ Chess" + Xpos + "" + YPOS + "" + ChessColor); Méthode de la victoire, et le paramètre est passé comme des échecs noirs IsmousEenabled = false; Firthread.SendMessage ("/" + ChessPeername + "/ Chess" + XPOS + "" + YPOS + "" + ChessColor); XPOS + "+ YPOS +", c'est le tour de Black. "); 7, 16); SetLocation (XPOS, YPOS, ChessColor); Statustext.setText ("Black (Thread" + ChessBlackCount + "Step)" + XPOS + "" + YPOS + ", c'est le carré blanc."); Firpblack.setbounds (xpos * 20 - 7, yPos * 20 - 7, 16); firpwhite.setbounds (xpos * 20 - 7, ypos * 20 - 7, 16, 16); + ChessColor); Inputevent.button1_mask) {Chessx_pos = (int) e.getx (); chessy_pos = (int) e.gety (); Chessy_Pos / 20> 19) {// Aucune action n'est effectuée lorsque la position d'échecs est incorrecte} else {PaintFirpoint (A, B, ChessColor); public void Mouseclicked (Mouseevent E) {} public void ActionPerformed (ActionEvent E) {}} 4. Développer des fils d'échecs
import java.util.stringtokenizer; Importer java.io.ioException; / ** * Créé par l'administrateur sur 2016/11/21. * / classe publique Firthread étend Thread {Firpad CurrPad; // La carte d'échecs du thread actuel public Firthread (firpad currpad) {this.currpad = currpad; } // Traitez les informations obtenues publiques void DealWithMsg (String Msgreeveived) {if (Msgreeveived.startsWith ("/ Chess")) {// Les informations reçues sont Chess StringTokenizer UserMsgToken = new StringTokenizer (MsGreceived, ""); // Le tableau des informations sur les pièces d'échecs et 0 index sont: x coordonnées; 1 bit d'index: coordonnée y; 2 Index Bit: ChessInfo = {"-1", "-1", "0"}; int i = 0; // Flag Bit String ChessInfotoken; while (userMsgToken.hasmoretokens ()) {ChessInfotoken = (String) userMsgToken.NextToken (""); if (i> = 1 && i <= 3) {ChessInfo [i - 1] = ChessInfotoken; } i ++; } currpad.paintNetFirPoint (Integer.ParseInt (ChessInfo [0]), Integer .ParseInt (ChessInfo [1]), Integer.ParseInt (ChessInfo [2])); } else if (MgrEceived.startswith ("/ yourname")) {// Le message reçu est renommé currpad.chesselfname = Msgreceived.Substring (10); } else if (mgreeveived.equals ("/ error")) {// Le message d'erreur reçu est currpad.statustext.setText ("l'utilisateur n'existe pas, veuillez vous réjouir!"); }} // Envoyer le message public void sendMessage (String sndMessage) {try {currpad.outputdata.writeUtf (sndMessage); } catch (exception ea) {ea.printStackTrace () ;; }} public void run () {String msGreceived = ""; essayez {while (true) {// attendez les informations d'entrée msgreceived = currpad.inputdata.readutf (); DealWithMsG (MGRECECEIVE); }} catch (ioException es) {}}} Commencez à développer le module du serveur ci-dessous
1. Développer le panneau d'information du serveur
import java.awt.borderLayout; import java.awt.color; import java.awt.flowlayout; import java.awt.label; import java.awt.panel; Importer java.awt.TextArea; import javax.swing.jlabel; / ** * Créé par l'administrateur sur 2016/11/21. * / public class servermsgpanel étend le panneau {public textarea msgTextArea = new TextArea ("", 22, 50, textarea.scrollbars_vertical_only); public JLabel StatusLabel = new JLabel ("Connexions actuelles:", label.left); panneau public msgpanel = nouveau panneau (); Panel Panel StatusPanel = nouveau panneau (); public servermsGpanel () {setSize (350, 300); SetBackground (Color.light_Gray); setLayout (new BorderLayout ()); msgpanel.setLayout (new FlowLayout ()); msgpanel.setSize (210, 210); StatusPanel.SetLayout (new BorderLayout ()); StatusPanel.SetSize (210, 50); msgpanel.add (msgTextArea); StatusPanel.Add (StatusLabel, BorderLayout.West); Add (msgpanel, borderlayout.center); add (statuspanel, borderlayout.north); }} 2. Développer le processus de serveur
import java.io.datainputStream; import java.io.dataOutputStream; Importer java.io.ioException; import java.net.socket; Importer Java.util.Enumeration; import java.util.hashTable; import java.util.stringtokenizer; / ** * Créé par l'administrateur sur 2016/11/21. * / classe publique FirServerThread étend Thread {Socket Clientsocket; // Enregistrer les informations sur le socket client hashtable ClientDatahash; // Enregistrer le hashtable ClientNameHash correspondant au port client et au flux de sortie; // Enregistrez le hashtable Chesspeerhash correspondant au socket client et au nom du client; // Enregistrer le hash servermsgpanel correspondant au créateur de jeux et à la menuiserie; Boolean isClientClosed = false; public FirserverThread (Socket ClientSocket, HashTable ClientDatahash, HashTable ClientNameHash, HashTable ChessPeerHash, ServerMsGpanel Server) {this.clientsocket = ClientSocket; this.clientDatahash = clientDatahash; this.clientNameHash = clientNameHash; this.chesspeerhash = Chesspeerhash; this.servermsgpanel = server; } public void DealWithmsg (String msGreceived) {String clientName; String Peername; if (Msgreceived.startswith ("/")) {if (Msgreceived.equals ("/ list")) {// Les informations reçues consistent à mettre à jour la liste des utilisateurs Feedback (GetUserList ()); } else if (MgrEceived.startsWith ("/ CreatGame [Inchess]")) {// Le message reçue est de créer la chaîne de jeu gameCreAnterName = MGRECECEived.SubString (20); // obtient le nom du serveur synchronisé (clientNameHash) {// Mettez le port utilisateur dans la liste d'utilisateurs clientNameHash.put (clientSocket, Msgreceived.SubString (11)); } synchronisé (ChesspeerHash) {// Définissez l'hôte sur l'état d'attente Chesspeerhash.put (GameCreAnterName, "Wait"); } Feedback ("/ yourname" + clientNameHash.get (clientSocket)); sendGamePeermsg (gameCreAnternAme, "/ ok"); sendPublicmsg (getUserList ()); } else if (MgrEceived.startswith ("/ jOningame")) {// Le message reçu est lors de la joie du jeu StringTokenizer usertokens = new StringTokenizer (MSGRECECEIVE, ""); Chaîne usertoken; String GameCreatorName; String GamePatiCantName; String [] playernames = {"0", "0"}; int nameIndex = 0; while (usertokens.hasmoretokens ()) {userKink = (String) usertokens.nextToken (""); if (nameIndex> = 1 && nameIndex <= 2) {playernames [nameIndex - 1] = usertoken; // Obtenez la vie du lecteur} nameIndex ++; } gameCreatorName = Playernames [0]; GamePatiCantName = Playernames [1]; if (chesspeerhash.containskey (gameCreatorName) && chesspeerhash.get (gameCreatorName) .equals ("wait")) {// Le jeu a été créé synchronisé (clientNamehash) {// ajouter le client correspondant); } synchronisé (ChessPeerHash) {// Ajouter ou modifier le ChesspeerHash.put correspondant (GameCreatorName, GamePaticantName); } sendPublicmsg (getUserList ()); // Envoyez un message à la menuiserie SendGamePeermsg (GamePaticantName, ("/ Peer" + "[Inchess]" + GameCreatorName)); // Envoyez le jeu au jeu Créateur SendGamePeermsg (GameCreatorName, ("/ Peer" + "[Inchess]" + GamePaticApantName)); } else {// Si le jeu n'est pas créé, le jeu est refusé d'être ajouté SendGamePeermsg (GamePatiCantName, "/ rejeter"); essayez {closEClient (); } catch (exception ez) {ez.printStackTrace (); }}} else if (Msgreceived.startswith ("/ [inchess]")) {// Le message reçu est int premierLocation = 0, LastLocation; LastLocation = MgrEceived.Indexof ("", 0); peername = MGRECECEIVE.SUBSTRING ((FirstLocation + 1), LastLocation); MSGRECEIVE = MGRECECEIVE.SUBSTRING ((LastLocation + 1)); if (SendGamePeerMsg (peername, MgrEceived)) {feedback ("/ error"); }} else if (mgreceived.startswith ("/ givep")) {// Le message reçu est lorsque vous abandonnez la chaîne de jeu ChessClientName = MGRECECEIVE.SUBSTRING (8); if (ChesspeerHash.ContainsKey (ChessClientName) &&! ((String) ChesspeerHash.get (ChessClientName)) .Equals ("Wait")) {// Le gagnant est le Joiner Game, envoyez le message de victoire SendGamePeerMSG ((string) ChessPeerHash.get (ChessClientName), "/ Youwin"); synchronisé (ChesspeerHash) {// Supprimer l'utilisateur quitte le jeu chesspeerhash.remove (ChessClientName); }} if (chesspeerhash.containsvalue (ChessClientName)) {// Le gagnant est le créateur de jeu et envoie le message de victoire sendgamepeermsg ((string) gethashkey (ChessPeerHash, ChessClientName), "/ youwin"); synchronisé (ChesspeerHash) {// Supprimer l'utilisateur Quit le jeu Chesspeerhash.reMove ((String) Gethashkey (ChesspeerHash, ChessClientName)); }}} else {// Lorsque les informations reçues sont d'autres informations int lastLocation = msgreceived.indexof ("", 0); if (lastLocation == -1) {feedback ("Command invalid"); retour; }}} else {MSRECECEived = clientNameHash.get (ClientSocket) + ">" + MSRECECEIVE; servermsgpanel.msgTextArea.APPEND (MGRECECEIVE + "/ N"); sendPublicmsG (MGRECECEived); servermsgpanel.msgTextArea.setCaretPosition (servermsgpanel.msgTextArea.getText () .length ()); }} // Envoi public void SendPublicmsG (String publicmsg) {synchronisé (clientDatahash) {for (énumération enU = clientDatahash.Elements (); enU .hasmoreelements ();) {dataOutputStream outputData = (dataoutputStream) enU.Nexelement (); essayez {outputData.writeUtf (publicmsg); } catch (ioException es) {es.printStackTrace (); }}}}} // Envoyez des informations à l'utilisateur dans le jeu spécifié public booléen sendgamepeermsg (String GamePeertarget, String GamePeermsg) {pour (énumération enU = clientDatahash.keys (); enu.hasmoreelements ();) {// travers) enU.NextElement (); if (gamepeertarget.equals ((string) clientNamehash.get (userlient)) &&! GamePeertarget.equals ((String) ClientNamehash .get (ClientSocket))) {// Synchronisé (clientDatahash) {// Créer des données Stream DataUtStream. essayez {// envoyer des informations 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.开发服务器端
importer 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); } }); paquet(); setVisible(true); setSize(400, 300); setResizable(false); valider(); 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.*; importer java.io. *; import java.net.*; import javax.swing.jframe; import djr.chess.gui.UserChatPad; import djr.chess.gui.UserControlPad; import djr.chess.gui.UserInputPad; import djr.chess.gui.UserListPad; import djr.chess.pad.FIRPad; /** * Created by Administrator on 2016/11/21. */ public class FIRClient extends Frame implements ActionListener,KeyListener { // 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); paquet(); 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; Retour Vrai; } 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.开发客户端线程
Importer 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){} } }至此,网络版五子棋就算是开发完成了。关于这么多类和包的关系如下图:
Ce qui précède est tout le contenu de cet article. J'espère que cela sera utile à l'apprentissage de tous et j'espère que tout le monde soutiendra davantage Wulin.com.