Este artículo comparte el código específico para la versión en línea de Goziqi de implementación de Java para su referencia. El contenido específico es el siguiente
Análisis de requisitos:
Para el goji en línea, las siguientes funciones deben agregarse basadas en el goji ordinario:
1. Tenga un lado del servidor y un cliente. Después de que los usuarios inician sesión en el servidor a través del cliente, pueden jugar con otros usuarios iniciados.
2. El servidor admite múltiples grupos de usuarios para jugar al mismo tiempo
3. Los usuarios pueden crear nuevos juegos en el servidor o unirse a los juegos creados.
4. Los usuarios pueden chatear y comunicarse mientras juegan ajedrez
De lo anterior, podemos conocer las funciones que deben implementarse:
・ Proporcionar funciones de servidor y cliente
・ El servidor monitoreará el estado de inicio de sesión del cliente y permitirá que varios clientes inicien sesión
・ Los usuarios pueden iniciar sesión en el servidor a través del cliente, y luego pueden ver a otros usuarios del servidor actualmente en línea y chatear con ellos, etc.
・ Después de iniciar sesión en el servidor, los usuarios pueden crear un nuevo juego de Gozi o unirse al juego Gozi creado.
・ Los usuarios pueden jugar con otros usuarios como el Goji ordinario a través del cliente
Según la función, el Gochi de red se divide en 4 módulos: a saber, el módulo del panel de usuario, el módulo del panel de tablas, el módulo del servidor Gochi y el módulo de cliente de Gochi
Comencemos a compilar el módulo del panel de usuario:
1. Desarrollar el panel de la lista de usuarios
import java.awt.*; /*** Creado por el administrador el 2011/11/21. */// En el estado inicial, se agregarán 10 información llamada "No Usuario" a la lista, lo que indica que el servidor admite hasta 10 usuarios en línea al mismo tiempo.//La lista se agrega al panel, utilizando el formato de diseño "BorderLayout" de la clase pública ListPad extiende el panel {Lista de usuarios de la lista pública = nueva lista (10); public userListPad () {setLayout (new BorderLayout ()); for (int i = 0; i <10; i ++) {userList.add (i+"."+"No user"); } add (UserList, BorderLayout.Center); }} 2. Desarrollar el panel de chat de usuario
import javax.swing.*; import java.awt.*; /*** Creado por el administrador el 2011/11/21. */// El panel de chat es un control TextAREA View con una barra de desplazamiento vertical. // El TextAREA se agrega al panel, utilizando el formato de diseño "BorderLayout". UserChatPad de la clase pública extiende JPanel {public JTextArea ChattextArea = new JTexTarea ("Área de comando", 18,20); Public UserChatPad () {setLayout (new BorderLayout ()); ChattextArea.SetAUTOSCROLLS (verdadero); ChattextArea.setLineWrap (verdadero); add (ChattextArea, BorderLayout.Center); }} 3. Desarrollar el panel de entrada del usuario
import javax.swing.*; import java.awt.*; /*** Creado por el administrador el 2011/11/21. */// El panel contiene dos controles de vista // ContentInpited es un control de campo TextField, donde los usuarios pueden ingresar información de chat de clase pública UserInputPad extienden jpanel {public jTextfield ContentInputTed = new JTextField ("", 26); public JComboBox UserChoice = new JComboBox (); Public UserInputPad () {setLayout (new FlowLayout (FlowLayout.left)); for (int i = 0; i <50; i ++) {userChoice.Additem (i+"."+"No user"); } UserChoice.SetSize (60,24); agregar (userChoice); agregar (contentInputTed); }} 4. Desarrollar el panel de operación del usuario
import javax.swing.*; import java.awt.*; /*** Creado por el administrador el 2011/11/21. */ public class Usercontrolpad extiende JPanel {public JLabel iplabel = new JLabel ("IP", JLabel.left); public JTextfield ipinputTTE = new JTextfield ("localhost", 10); public JButton ConnectButton = new JButton ("Connect al servidor"); public JButton createButton = new JButton ("Crear juego"); público JButton JoinButton = new JButton ("Juego de unión"); público JButton CancelButton = new JButton ("Give Up Game"); public JButton ExitButton = new JButton ("Juego de salida"); public UserControlPad () {setLayout (new FlowLayout (FlowLayout.left)); setbackground (color.light_gray); agregar (iPlabel); agregar (ipinputted); Agregar (ConnectButton); add (createButton); Agregar (JoinButton); agregar (cancelarButton); Agregar (ExitButton); }} Comience a desarrollar el módulo del panel de la junta a continuación
1. Desarrolle el ajedrez negro
import java.awt.*; /*** Creado por el administrador el 2011/11/21. */ public class Firpointblack extiende lienzo {Firpad Padbelonged; // El tablero a la que el ajedrez negro pertenece públicamente Firpointblack (Firpad Padbelonged) {SetSize (20, 20); // establece el tamaño de la pieza de ajedrez esto. } public void Paint (Graphics g) {// Dibuja la pieza de ajedrez G.SetColor (color.black); G.Filloval (0, 0, 14, 14); }} 2. Desarrollar la categoría de ajedrez blanco
import java.awt.*; /*** Creado por el administrador el 2011/11/21. */ public class Firpointwhite extiende lienzo {Firpad Padbelonged; // El tablero a la que el ajedrez blanco pertenece públicamente Firpointwhite (Firpad Padbelonged) {SetSize (20, 20); this.padbelonged = Padbelonged; } public void Paint (Graphics g) {// dibujar piezas de ajedrez G.SetColor (color.white); G.Filloval (0, 0, 14, 14); }} 3. Desarrolle un panel de tablero de ajedrez
import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import javax.swing.jTextfield; /*** Creado por el administrador el 2011/11/21. */ Public Class FirPad extiende Panel Implements MouseListener, ActionListener {// ¿Se puede usar el mouse público boolean isMouseenable = false; // si ganar públicamente boolean iswinned = false; // si jugar al ajedrez público boolean isgaming = false; // bits de coordenadas del eje x de la pieza de ajedrez public int chessx_pos = -1; // y -eje y bits de coordenadas de la pieza de ajedrez public int Chessy_pos = -1; // Color de la pieza de ajedrez public int Chesscolor = 1; // matriz de bits de coordenadas de eje x negro // matriz de bits de coordenadas de eje negro público int Chessblack_ypos [] = new int [200]; // Array de bits de coordenadas de eje y blanca public int Chesswhite_xpos [] = new int [200]; // COUNTIVO DE ACHIVO BLANCO COORDINADA DIGIT MATRAY Public int Chesswhite_ypos [] = new int [200]; // Número de ajedrez negro público int ChessblackCount = 0; // Número de ajedrez blanco en público int Chesswhitecount = 0; // Número de ajedrez negro gana pública int ChessblackVictimes = 0; // Número de ajedrez blanco gana pública int ChesswhiteVictimes = 0; // Número de ajedrez blanco gana pública int ChesswhiteVictimes = 0; // Interfaz de manga Socador Public Socket Cheessocket; Public DatainPutStream InputData; Public DataOutputStream outputData; Cadena pública CHESSELFNAME = NULL; String public String Chesspeername = NULL; Public String Host = NULL; PUBLIC INT PORT = 4331; Public TextField StatusText = new TextField ("¡Conéctese al servidor!"); public STrthread firthread = new firthread (this); public firpad () {setSize (440, 440); setLayout (nulo); setbackground (color.light_gray); addMouselistener (esto); agregar (StatusText); StatusText.setBounds (nuevo rectángulo (40, 5, 360, 24)); StatusText.setEditable (falso); } // Conéctese al host público boolean ConnectServer (String Serverip, int serverport) lanza excepción {try {// Obtener el puerto host Chesssocket = new Socket (ServerIP, ServerPort); // Obtener el flujo de entrada inputData = new DataInputStream (Chesssocket.getInputStream ()); // get outputData = new DataOutputStream (Chesssocket.getOutputStream ()); firthread.start (); devolver verdadero; } catch (ioException ex) {statusstext.settext ("Conexión fallida! /n"); } return false; } // Establezca el estado de la junta al ganar public void setVicStatus (int vicchesscolor) {// borrar el tablero this.removeall (); // Establezca la posición de ajedrez negra en cero para (int i = 0; i <= ChessblackCount; i ++) {Chessblack_xpos [i] = 0; Chessblack_ypos [i] = 0; } // Establezca la posición del ajedrez blanco en cero para (int i = 0; i <= shesswhitecount; i ++) {Chesswhite_xpos [i] = 0; Chesswhite_ypos [i] = 0; } // Borrar el número de ajedrez negro en la placa ChessblackCount = 0; // borrar el número de ajedrez blanco en el tablero de ajedrezwhitecount = 0; agregar (StatusText); StatusText.setBounds (40, 5, 360, 24); if (vicchessColor == 1) {// Black Achess gana ChessblackVictimes ++; StatusText.settext ("Negro, negro: blanco" + ChessblackVicteimes + ":" + ChesswhitEvictimes + ", reiniciar el juego, esperar a White ..."); } else if (vicchessColor == -1) {// White Achess gana ChesswhitEvictimes ++; StatusText.settext ("Negro: White" + ChessblackVictimes + ":" + ChesswhitEvictimes + ", reiniciar el juego, esperar por negro ..."); }} // Obtenga la posición de la pieza de ajedrez especificada public void setLocation (int xPos, int ypos, int ChessColor) {if (ChessColor == 1 1) {// cuando la pieza de ajedrez es negra, Chessblack_xpos [ChessblackCount] = xPos * 20; Chessblack_ypos [ChessblackCount] = yPos * 20; ChessblackCount ++; } else if (ChessColor == -1) {// Cuando la pieza de ajedrez es blanca, Chesswhite_xpos [Chesswhitecount] = XPOS * 20; Chesswhitecount ++; }} // Determinar si el estado actual es un estado público ganador boolean checkvicStatus (int xPos, int ypos, int chesscolor) {int chesslinkedCount = 1; // Número de ChessLinkedCompare conectado = 1; // Solía comparar si desea continuar atravesando una pieza int chessTocompareIndex = 0; // La posición de índice de la pieza que se comparará int CloseGrid = 1; // La posición de la cuadrícula adyacente if (ChessColor == 1) {// ChesslinkedCount = 1; // Si se cuenta la pieza de ajedrez en sí, el número inicial de conexiones es 1 // cada par de declaraciones de bucle a continuación es un grupo, porque la posición del siguiente período puede estar en el medio en lugar de en ambos extremos para (CloseGrid = 1; CloseGrid <= 4; CloseGrid ++) {// Transipar a través de 4 Cuadrot adyacentes para (CheStOcompeIndex = 0; ChesstocActOCOCTOCOCTOCOCTOCOCTOCTOMBLACTAUNDEX. CHESSTOCOMPAREInEx ++) {// Transipate a través de todas las piezas de ajedrez negras en el tablero if ((((XPOS+CloseGrid) * 20 == CHESSBLACK_XPOS [CHESSTOCOMPAREDEX]) && ((YPOS * 20) == Chessblack_yPos [ChessTocompareIndex])) {// Determine si las cuatro piezas de Chess de la derecha de la derecha de la derecha de la derecha de la derecha de la derecha de la derecha de la derecha actualmente = ChesslinkedCount + 1; // Agregue 1 al número de conexiones if (ChessLinkedCount == 5) {// Cuando las cinco piezas están conectadas, la victoria devuelve verdadera; }}}} if (ChessLinkedCount == (ChessLinkedCompare+1)) {ChessLinkedCompare ++; } else {// Si hay una pieza de ajedrez en el medio que no es negra, entrará en esta rama y no hay necesidad de volver a romperse en este momento; }} para (CloseGrid = 1; CloseGrid <= 4; CloseGrid ++) {for (ChessTocomPareIndex = 0; ChessTocompareIndex <= ChessblackCount; ChessTocompareIndex ++) {if ((((XPOS - Closegrid) * 20 == CHESSBLACK_XPOS [CHESSTOCEINEX] &&&&&&&2 Chessblack_ypos [ChessTocompareIndex])) {// Determinar si las cuatro piezas de ajedrez a la izquierda de la actualmente tocando ChesslinkedCount ++; if (ChessLinkedCount == 5) {return true; }}}} if (ChessLinkedCount == (ChessLinkedCompare+1)) {ChessLinkedCompare ++; } else {break; }} // Al ingresar un nuevo conjunto de bucles, reinicie el número de conexiones, etc. ChesslinkedCount = 1; ChessLinkedCompare = 1; para (para (CloseGrid = 1; CloseGrid <= 4 = 4; CloseGrid ++) {para (ChessTocompareIndex = 0; ChessTocompareIndex <= ChessBlackCount; CheStocomPareIndex ++) {if (((XPOS * 20 == CHESSBLACK_XPOS [CHESSTOCOCOCTOINDEX]) && ((YPOS+CLOSER) * 20 == 20 == 20 == 20 == 20 == 20 == Chessblack_ypos [ChessTocompareIndex])) {// Determinar si las 4 piezas principales de la actualmente jugando a ChesslinkedCount ++; if (ChessLinkedCount == 5) {return true; }}} if (ChessLinkedCount == (ChessLinkedCompare+1)) {ChessLinkedCompare ++; } else {break; }} para (CloseGrid = 1; CloseGrid <= 4; CloseGrid ++) {for (ChessTocomPareIndex = 0; ChessTocompareIndex <= ChessblackCount; ChessTocompareIndex ++) {if ((XPOS * 20 == CHESSBLACK_XPOS [CHESSTOCOMPAREDEX]) && ((YPOS) Chessblack_ypos [ChessTocompareIndex])) {// Determine si las cuatro piezas debajo de la actualmente se reproducen ChessLinkedCount ++; if (ChessLinkedCount == 5) {return true; }}} if (ChessLinkedCount == (ChessLinkedCompare+1)) {ChessLinkedCompare ++; } else {break; }} ChesslinkedCount = 1; ChessLinkedCompare = 1; para (CloseGrid = 1; CloseGrid <= 4; CloseGrid ++) {for (ChessTocomPareIndex = 0; ChessTocompareIndex <= ChessBlackCount; ChessTocomPareIndex ++) {if ((((((XPOS - CloseGrid) * 20 == CHESSBLACK_XPOS [CHESSTOCOM ChessBlack_ypos [ChessTocompareIndex])) {// Determinar las cuatro piezas de ajedrez en la dirección superior de la izquierda de la actualmente tocando ChesslinkedCount ++; }} para (CloseGrid = 1; CloseGrid <= 4; CloseGrid ++) {for (ChessTocomPareIndex = 0; ChessTocompareIndex <= CHESSBLACKCOUNT; CHESSTOCOMPAREINEX ++) {if ((((XPOS+CloseGrid) * 20 == CHESSBLACK_XPOS [CHESSTOCAINDEX] && (Y (YPOS - (YPOS (YPOS (YPOS - (YPOS - (YPOS - (YPOS) 20 == Chessblack_ypos [CHESSTOCOMPAREDEX])) {// Determine las cuatro piezas de ajedrez en la dirección derecha de la pieza de ajedrez actual son negros ChesslinkedCount ++ if (ChessLinkedCount == 5) {return true } else {break; CHESSBLACK_XPOS [CHESSTOCOMPAREDEX]) && ((YPOS+CloseGrid) * 20 == CHESSBLACK_YPOS [CHESSTOCOMPAREDEX]) {// Determinar si las cuatro piezas de ajedrez en la dirección superior correcta de la pieza de ajedrez actual son negros de ajedrez ++; (ChessLinkedCount == (ChessLinkedCompare+1)) {ChessLinkedCompare ++; (((XPOS - CloseGrid) * 20 == CHESSBLACK_XPOS [CHESSTOCOMPAREDEX]) && ((YPOS - CloseGrid) * 20 == CHESSBLACK_YPOS [CHESSTOCOMPAREDEX])) {// Determinar si las cuatro piezas de ajedrez en la dirección inferior izquierda de la pieza actual de Chess son negras de CHessLinked ++; return true; (chessTocompareIndex = 0; chessTocompareIndex <= ChesswhiteCount; ChessTocompareIndex ++) {if (((XPOS+CloseGrid) * 20 == CHESSWHITE_XPOS [CHESSTOCOCHOPAREDEX] && (YPOS * 20 == CHESSWHITE_YPOS [CHESSTOCHOM de la actualmente tocando ChessLinkedCount ++; (chessTocompareIndex = 0; chessTocompareIndex <= thesswhiteCount; chessTocompareIndex ++) {if (((xPos - CloseGrid) * 20 == CHESSWHITE_XPOS [CHESSTOCOCHOCHOM de la actualmente tocada <= 4; Chesswhite_ypos [CHESSTOCOMPAREDEX])) {// Determinar las 4 piezas principales de la actualmente jugada (CloseGrid = 1; CloseGrid <= 4; CloseGrid ++) {for (ChessTocomPareIndex = 0; ChessTocompareIndex <= ChesswhiteCount; ChessTocomPareIndex ++) {if (((XPOS * 20 == CHESSWHITE_XPOS [CHESSTOCOPTOM Chesswhite_ypos [ChessTocompareIndex])) {// Determinar las cuatro piezas debajo de la actualmente jugada. ChesslinkedCount = 1; Chesswhite_xpos [ChessTocompareIndex]) && ((YPOS+CloseGrid) * 20 == Chesswhite_ypos [CHESSTOCOMPAREDEX])) (ChessLinkedCount == (ChessLinkedCompare+1)) {ChessLinkedCompare ++; (((XPOS+CloseGrid) * 20 == CHESSWHITE_XPOS [CHESSTOCOMPAREDEX]) && ((YPOS - CloseGrid) * 20 == CHESSWHITE_YPOS [CHESSTOCOMPAREDEX])) {// Determinar las cuatro piezas de ajedrez en la dirección derecha inferior de la pieza actual de Chess son blancos. return true; ChessTocompareIndex <= ChesswhiteCount; La pieza de ajedrez son blancas ChesslinkedCount ++; (chessTocompareIndex = 0; ChessTocompareIndex <= ChesswhiteCount; ChessTocompareIndex ++) {if (((XPOS - CloseGrid) * 20 == CHESSWHITE_XPOS [CHESSTOCOCHOCHOCMAINDEX]) && ((YPOS - CloseRid) * 20 == CHESSWHITE_YPOS [CHESSTOCOCMAM Las cuatro piezas en la dirección inferior a la izquierda de la actualmente tocada pintura (gráficos g) {para (int i = 40; i <= 380; i = i + 20) {G.Drawline (40, I, 400, i); 400, 400); // Dibuja AchessPawn Public Void PaintFirpoint (int XPOS, int YPOS, int ChessColor) {FirPointblack FirpBlack = new FirPointBlack (this); ChessColor); // Agregar piezas de ajedrez al tablero Firpblack.setBounds (XPOS * 20 - 7, YPOS * 20 - 7, 16, 16); else {// Win State FirThread.SendMessage (" /" + ChesspeNeName + " /Aches Parámetro aprobado como victoria de ajedrez negro isMouseenLed = false; firthread.sendMessage (" /" + Chesspeername + " /Ajedido" + XPOS + "" + YPOS + "" + CHESSCOLOR); XPOS + " + YPOS +", es el turno de negro "); 7, 16, 16); SetLocation (XPOS, YPOS, ChessColor); StatusText.Settext ("Black (Thread" + ChessblackCount + "Step)" + XPOS + "" + YPOS + ", es el cuadrado blanco"); 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) {// No se realiza una acción cuando la posición de ajedrez es incorrecta} else {pintarFirpoint (a, b, thesscolor); public void Mouseclicked (MouseEvent E) {} public void Actionperformed (ActionEvent E) {}} 4. Desarrollar hilos de tablero de ajedrez
import java.util.stringTokenizer; import java.io.ioException; /*** Creado por el administrador el 2011/11/21. */ public class firthread extiende el hilo {firpad currpad; // La placa de ajedrez del hilo actual public STRTHREAD (FirPad Currpad) {this.currpad = CurrPad; } // Procesar la información obtenida public void DealwithMsg (String MSGRECEIVE) {if (msgreceive.Startswith ("/Chess")) {// La información recibida es ajedrez stringTokenizer usermsgToken = new StringTokenizer (msgreceived, ""); // La matriz de información de piezas de ajedrez y 0 índices son: x coordenadas; 1 bit de índice: y coordenada; 2 bit de índice: Chessinfo = {"-1", "-1", "0"}; int i = 0; // Cadena de bits de bandera 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 (msgreceive.startswith ("/yourname")) {// El mensaje recibido se renombra a CurrPad.ChessSelfName = MSGRECEive.Substring (10); } else if (msgreceive.equals ("/error")) {// El mensaje de error recibido es CurrPad.StatusText.SetText ("El usuario no existe, ¡reorreselo!"); }} // Enviar el mensaje public void sendMessage (String sndMessage) {try {CurrPad.outputData.Writeutf (SndMessage); } Catch (Exception EA) {EA.PrintStackTrace () ;; }} public void run () {String MSGRECEIVED = ""; Pruebe {while (true) {// espere información de entrada msgreceived = currpad.inputData.readutf (); DealWithMsg (MSGRECEIVED); }} catch (ioException es) {}}} Comience a desarrollar el módulo del servidor a continuación
1. Desarrollar el panel de información del servidor
import java.awt.borderlayut; import java.awt.color; import java.awt.flowlayout; import java.awt.label; import java.awt.panel; import java.awt.textarea; import javax.swing.jlabel; /*** Creado por el administrador el 2011/11/21. */ public class ServermsGpanel extiende el panel {Public TextARea msgtexTarea = new TextARea ("", 22, 50, TextAREA.ScrollBars_vertical_only); public jlabel statusLabel = new JLabel ("Conexiones actuales:", Label.left); panel público msgpanel = new Panel (); Panel público statusPanel = new Panel (); Public servermsgpanel () {setSize (350, 300); setbackground (color.light_gray); setLayout (new BorderLayout ()); msgpanel.setLayout (new FlowLayout ()); msgpanel.setsize (210, 210); statusPanel.setLayout (new BorderLayout ()); statuspanel.setsize (210, 50); msgpanel.add (msgTextArea); statuspanel.add (StatusLabel, BorderLayout.West); agregar (msgpanel, borderLayout.center); add (StatusPanel, BorderLayout.north); }} 2. Desarrollar el proceso del servidor
import java.io.datainputstream; import java.io.dataOutputStream; import java.io.ioException; import java.net.socket; importar java.util.enerumeration; import java.util.hashtable; import java.util.stringTokenizer; /*** Creado por el administrador el 2011/11/21. */ public class FirServerThread extiende el subproceso {Socket ClientSocket; // Guardar información de socket de cliente Hashtable ClientDatahash; // Guarde el hash hashtable ClientNameHash correspondiente al puerto del cliente y al flujo de salida; // Guarde el hash hashtable Chesspeerhash correspondiente al socket del cliente y al nombre del cliente; // Guardar el hash servermsgpanel correspondiente al creador del juego y al cariñador del juego; 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 = servidor; } public void DealwithMsg (String MSGreceive) {String ClientName; Cadena peername; if (msgreceive.startswith ("/")) {if (msgreceive.equals ("/list")) {// La información recibida es actualizar los comentarios de la lista de usuarios (getUserList ()); } else if (msgreceive.startswith ("/createGame [Inchess]")) {// El mensaje recibido es crear el juego String GameCrealtername = MSGRECEive.Substring (20); // Obtenga el nombre del servidor sincronizado (ClientNameHash) {// Ponga el puerto de usuario en la lista de usuarios ClientNameHash.put (Clientsocket, msgreceive.substring (11)); } SynChronized (Chesspeerhash) {// Establezca el host en Wait State ChesspeerHash.put (GameCreAtername, "Wait"); } Retroalimentación ("/YourName" + ClientNameHash.get (ClientSocket)); sendgamePeermsg (GamecreAtername, "/OK"); sendPublicmsg (getUserList ()); } else if (msgreceive.startswith ("/Joingame")) {// El mensaje recibido es cuando se une al juego StringTokenizer userTokens = new StringTokenizer (msgreceived, ""); Cadena 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; // Obtener la vida del jugador} nameIndex ++; } gamecreatorname = playernames [0]; gamePaticipantName = Playernames [1]; if (Chesspeerhash.ContainsKey (GameCreatorname) && Chesspeerhash.get (GameCreatorname) .Equals ("Wait")) {// El juego se ha creado sincronizado (ClientNameHash) {// Agregar el cliente correspondiente. } sincronizado (ChesspeerHash) {// Agregar o modificar el correspondiente ChesspeerHash.put (GameCreatorname, GamePaticipantName); } sendPublicmsg (getUserList ()); // Enviar mensaje al juego Juego SendGamePeermsg (GamePaticipantName, ("/peer" + "[Inchess]" + gamecreatorname)); // Envía el juego al creador del juego SendGamePeermsg (GameCreatorname, ("/Peer" + "[Inchess]" + GamePaticipantName)); } else {// Si el juego no se crea, el juego se niega a agregarse sendgamePeermsg (gamePaticipantName, "/rechazar"); intente {CloseClient (); } catch (excepción ez) {ez.printstackTrace (); }}} else if (msgreceive.startswith ("/[Inchess]")) {// El mensaje recibido es int firlLocation = 0, LastLocation; lastLocation = msgreceive.indexof ("", 0); peername = msgreceive.substring ((FirstLocation + 1), LastLocation); MSGRECEIVED = MSGRECEIVE.SUBString ((LastLocation + 1)); if (sendGamePeermSg (peername, msgreceived)) {folny ("/error"); }} else if (msgreceived.startswith ("/goundup")) {// El mensaje recibido es cuando renuncias a la cadena del juego ChessClientName = MSGRECEive.substring (8); if (ChesspeerHash.ContainsKey (ChessClientName) &&! (((String) Chesspeerhash.get (ChessClientName)) .Equals ("Wait")) {// El ganador es el Juego Joiner, envía el mensaje de la victoria SendGamePeermsg ((String) Chesspeerhash.get (ChessclastName), "/YouWin"); ");"); Synchronized (Chesspeerhash) {// Eliminar el usuario deja el juego Chesspeerhash.remove (ChessClientName); }} if (ChesspeerHash.ContainsValue (ChessClientName)) {// El ganador es el creador del juego y envía el mensaje de la victoria sendgamePeermsg ((string) gethashkey (Chesspeerhash, ChessClientName), "/youwin"); Synchronized (Chesspeerhash) {// Eliminar el usuario deja el juego Chesspeerhash.remove (((String) Gethashkey (Chesspeerhash, ChessClientName)); }}} else {// Cuando la información recibida es otra información int if (lastLocation == -1) {retroalimentación ("comando inválido"); devolver; }}} else {MSGRECEIVED = ClientNameHash.get (ClientSocket) + ">" + MSGRECEIVED; servermsgpanel.msgtexTarea.append (msgreceived + "/n"); sendPublicmsg (MSGReceive); servermsgpanel.msgtexTarea.setCaretPosition (servermsgpanel.msgtexTarea.gettext () .length ()); }} // Enviar public void sendPublicmsg (String publicMsg) {SynChronized (ClientDataHash) {for (enumeration enu = clientDatahash.elements (); enu .hasmoreelements ();) {datautputStream outputData = (datautputStream) enu.nextelement (); intente {outputData.WriteUtf (publicMsg); } catch (ioException es) {es.printStackTrace (); }}}}} // Enviar información al usuario en el juego especificado public boolean sendgamePeermsg (String gamePeerTarget, string gamePeermsg) {for (enumeration enu = clientDatahash.keys (); au.hasmoreelementsements ();) {// traverse para obtener la interfaz de Socket de la interfaz de juego de juego de juego () enu.nextelement (); if (gamePeerTarget.equals (((String) ClientNameHash.get (userClient)) &&! GamePeerTarget.equals ((String) ClientNameHash .get (ClientSocket)) {// SynChronized (ClientDataHah) {// Cree streamOutputPutStream PeeroutData = (DataSoutStream) ClientDatahash (get (get); Pruebe {// Enviar información PeeroutData.Writeutf (GamePeermsg); } catch (ioException es) {es.printStackTrace (); } } return false; }} return verdadero; } // 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); } }); embalar(); setVisible(true); setSize(400, 300); setResizable(false); validar(); try { createServer(4331, serverMsgPanel); } catch (Exception e) {E.PrintStackTrace (); } } // Create server with specified ports and panels public void createServer(int port, ServerMsgPanel serverMsgPanel) throws IOException { Socket clientSocket; // Client socket long clientAccessNumber = 1; // The number of clients connected to the host this.serverMsgPanel = serverMsgPanel; // Set the current host try { serverSocket = new ServerSocket(port); serverMsgPanel.msgTextArea.setText("Server started at:" + InetAddress.getLocalHost() + ":" //djr + serverSocket.getLocalPort() + "/n"); while (true) { // Listen to the information of the client socket clientSocket = serverSocket.accept(); serverMsgPanel.msgTextArea.append("Connected user:" + clientSocket + "/n"); // Create client output stream DataOutputStream outputData = new DataOutputStream(clientSocket .getOutputStream()); // Bind client socket and output stream clientDataHash.put(clientSocket, outputData); // Bind client socket and client name clientNameHash .put(clientSocket, ("New Player" + clientAccessNumber++)); // Create and run the server-side thread FIRServerThread thread = new FIRServerThread(clientSocket, clientDataHash, clientNameHash, chessPeerHash, serverMsgPanel); Thread.Start (); } } catch (IOException ex) { ex.printStackTrace(); } } public void actionPerformed(ActionEvent e) { if (e.getSource() == clearMsgButton) { // Clear server information serverMsgPanel.msgTextArea.setText(""); } if (e.getSource() == serverStatusButton) { // Show server information try { serverMsgPanel.msgTextArea.append("Server Information:" + InetAddress.getLocalHost() + ":" + serverSocket.getLocalPort() + "/n"); } catch (Exception ee) { ee.printStackTrace(); } } if (e.getSource() == closeServerButton) { // Close the server System.exit(0); } } public static void main(String args[]) { FIRServer firServer = new FIRServer(); }}下面开始编写客户端模块
1.开发客户端
import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; 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); embalar(); 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; devolver verdadero; } 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 ")) { // 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){} } }至此,网络版五子棋就算是开发完成了。关于这么多类和包的关系如下图:
Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.