Java network 50 source code

xiaoxiao2021-03-06  77

The following source code is divided into 4 files; checkclient.java: Client main program. ChessInterface.java: Client interface. Chesspad.java: Drawing of chessboard. ChessServer.java: server side. 50 people can be accommodated at the same time, and they are online, chatting. No detailed comments, but absolutely can be run, J2SDK1.4 is passed. / ************************************************** ******************************************** 1.ChessClient.java * *********************************************************** ************************************************************************** / Import Java.Awt. * Import java.awt.event. *; import java.io. *; import java.Net. *; import java.util. *;

Class Clientthread Extends Thread {ChessClient ChesClient;

CLIENTTHREAD (CgestClient ChessClient) {this.chestclient = insics;

Public void acceptmessage (string recmessage) {if (Recmessage.StartSwith ("/ userlist")) {StringTokenizer UserToken = New StringTokenizer (Recmessage, "); int usrnumber = 0;

chessclient.userpad.userList.removeAll (); chessclient.inputpad.userChoice.removeAll (); chessclient.inputpad.userChoice.addItem ( "owner"); while (userToken.hasMoreTokens ()) {String user = (String) userToken .NEXTTOKEN (""); if (usernumber> 0 &&! user.startswith ("[inchess")) {CHESSCLIENT.USERPAD.USERLIST.ADD (User); chessclient.inputpad.userchoice.additem (user);}

userNumber ;} chessclient.inputpad.userChoice.select ( "owner");} else if (recMessage.startsWith ( "/ yourname")) {chessclient.chessClientName = recMessage.substring (10); chessclient.setTitle ( "Java backgammon Client " " User Name: " ChessClient.ChessClientName);} else if (Recmessage.equals (" / reject ")) {Try {CHESSCLIENT.CHESSPAD.STATUSTEXT.SETTEXT (" You can't join the game "); chessclient.controlpad .cancelGameButton.setEnabled (false); chessclient.controlpad.joinGameButton.setEnabled (true); chessclient.controlpad.creatGameButton.setEnabled (true);} catch (Exception ef) {chessclient.chatpad.chatLineArea.setText ( "chessclient.chesspad. chessSocket.close not closed ");} chessclient.controlpad.joinGameButton.setEnabled (true);} else if (recMessage.startsWith (" / peer ")) {chessclient.chesspad.chessPeerName = recMessage.substring (6); if ( ChessClient.isserver) {chessclient.chesspad.chesscolor = 1; chessclient.chestpad.ismouseenabled = true; chessclient.chestpad.statustext.setText ("Please black chess"); } Else if (chessclient.isclient) {chassclient.chesspad.chesscolor = -1; chessclient.chestpad.statustext.setText ("Added game, wait for the other party ...");}

} Else if (recMessage.equals ( "/ youwin")) {chessclient.isOnChess = false; chessclient.chesspad.chessVictory (chessclient.chesspad.chessColor); chessclient.chesspad.statusText.setText ( "the other side to exit, please give up the game Exit connection "); chessclient.chentpad.ismouseenabled = false;} else if (" / ok ")) {chessclient.chestpad.statustext.setText (" Create a game success, wait for others to join ... "); } Else if ("/ error")) {chessclient.chatpad.chatlinearea.Append ("Transfer Error: Please exit the program, re-joining / N");} else {chessclient.chatpad.chatlinearea.Append (Recmessage "/ n"); chessclient.chatpad.chatlinearea.setcaretPosition (ChessClient.Chatpad (). Length ());}} public void run () {string message = ""; try {whele (true) { Message = chessclient.in.readutf (); acceptmessage (message);}} catch (ooException es) {}}

}

public class chessClient extends Frame implements ActionListener, KeyListener {userPad userpad = new userPad (); chatPad chatpad = new chatPad (); controlPad controlpad = new controlPad (); chessPad chesspad = new chessPad (); inputPad inputpad = new inputPad ();

Socket chatSocket; DataNputStream in; DataOutputStream out; string chessclientname = null; string host = null; int port = 4331;

Boolean isonchat = false; // chat? Boolean isonchess = false; // Chess? Boolean isgameconnected = false; / / The client connection of the chess? Boolean isserver = false; // If it is the host boolean isclient = false; // If it is a chess client

Panel SouthPanel = new panel (); Panel northpa = new panel (); panel centerpanel = new panel (); panel westpanel = new panel (); panel eastpanel = new panel ();

ChessClient () {Super ("Java Give Chess Client"); setLayout (New BorderLayout ()); host = controlpad.inputip.getText (); Westpanel.setLayout (New borderLayout ()); Westpanel.Add (UserPad, BorderLayout. North); WestPanel.Add (chatpad, borderlayout.center); WestPanel.SetBackground (Color.pink)

Inputpad.inputwords.addKeylistener (this); chesspad.host = controlpad.inputip.getText ();

CenterPanel.Add (Chesspad, BorderLayout.center); CenterPanel.Add (InputPad, BorderLayout.South); CenterPanel.setBackground; Color.pink;

controlpad.connectButton.addActionListener (this); controlpad.creatGameButton.addActionListener (this); controlpad.joinGameButton.addActionListener (this); controlpad.cancelGameButton.addActionListener (this); controlpad.exitGameButton.addActionListener (this);

ControlPad.creatgameButton.setenabled (false); controlpad.joingamebutton.setenabled (false); controlpad.cancelgamebutton.setenabled (false);

SouthPanel.Add (ControlPad, BorderLayout.center); SouthPanel.setBackground;

addWindowListener (new WindowAdapter () {public void windowClosing (WindowEvent e) {if (isOnChat) {try {chatSocket.close ();} catch (Exception ed) {}} if (isOnChess || isGameConnected) {try {chesspad.chessSocket .close ();} catch (Exception EE) {}} system.exit (0);} public void windowActivated (WindowEvent EA) {

}});

Add (WestPanel, BorderLayout.west); Add (CenterPanel, BorderLayout.center); Add (SouthPanel, BorderLayout.South);

Pack (); setsize (670, 548); setVisible (true); setResizable (false); validate ();

public boolean connectServer (String serverIP, int serverPort) throws Exception {try {chatSocket = new Socket (serverIP, serverPort); in = new DataInputStream (chatSocket.getInputStream ()); out = new DataOutputStream (chatSocket.getOutputStream ()); clientThread clientthread = new clientThread (this); clientthread.start (); isOnChat = true; return true;} catch (IOException ex) {chatpad.chatLineArea.setText ( "chessClient: connectServer: not connect, it is recommended to restart the program / n") Return False;}

public void actionPerformed (ActionEvent e) {if (e.getSource () == controlpad.connectButton) {host = chesspad.host = controlpad.inputIP.getText (); try {if (connectServer (host, port)) {chatpad. chatLineArea.setText ( ""); controlpad.connectButton.setEnabled (false); controlpad.creatGameButton.setEnabled (true); controlpad.joinGameButton.setEnabled (true); chesspad.statusText.setText ( "the connection is successful, create a game or join Game ");

} Catch (exception EI) {chatpad.chatlineArea.setText ("ControlPad.ConnectButton: Unable to connect, recommended reboot / n");}} f (E.getsource () == controlpad.exitgamebutton) {if (isonchat) {Try {chatsocket.close ();} catch (exception ed) {}} f (isonchess || isgameconnected) {try {chesspad.chessoscket.close ();} catch (exception ee) {}} system.exit (0 );

} If (e.getSource () == controlpad.joinGameButton) {String selectedUser = userpad.userList.getSelectedItem (); if (selectedUser == null || selectedUser.startsWith ( "[inchess]") || selectedUser.equals ( chessClientName)) {chesspad.statusText.setText ( "must select a valid user");} else {try {if (isGameConnected) {if (chesspad.connectServer (chesspad.host, chesspad.port)) {isGameConnected =! true; isOnChess = true; isClient = true; controlpad.creatGameButton.setEnabled (false); controlpad.joinGameButton.setEnabled (false); controlpad.cancelGameButton.setEnabled (true); chesspad.chessthread.sendMessage ( "/ joingame" userpad. userList.getSelectedItem () "" chessClientName);}} else {isOnChess = true; isClient = true; controlpad.creatGameButton.setEnabled (false); controlpad.joinGameButton.setEnabled (false); controlpad.cancelGameButton.set Enabled (true); chesspad.chessthread.sendMessage ( "/ joingame" userpad.userList.getSelectedItem () "" chessClientName);}} catch (Exception ee) {isGameConnected = false; isOnChess = false; isClient = false; controlpad.creatGameButton.setEnabled (true); controlpad.joinGameButton.setEnabled (true); controlpad.cancelGameButton.setEnabled (false); chatpad.chatLineArea.setText ( "chesspad.connectServer not connect / n" ee);}

}} If (e.getSource () == controlpad.creatGameButton) {try {if {if (chesspad.connectServer (chesspad.host, chesspad.port)) {isGameConnected = true (isGameConnected!); IsOnChess = true; isServer = true; controlpad.creatGameButton.setEnabled (false); controlpad.joinGameButton.setEnabled (false); controlpad.cancelGameButton.setEnabled (true); chesspad.chessthread.sendMessage ( "/ creatgame" "[inchess]" chessClientName);} } else {isOnChess = true; isServer = true; controlpad.creatGameButton.setEnabled (false); controlpad.joinGameButton.setEnabled (false); controlpad.cancelGameButton.setEnabled (true); chesspad.chessthread.sendMessage ( "/ creatgame" " [inchess] " chessClientName);}} catch (Exception ec) {isGameConnected = false; isOnChess = false; isServer = false; controlpad.creatGameButton.setEnabled (true); controlpad.joinGameButto n.setenable; controlpad.cancelgamebutton.setenabled (false); ec.printStackTrace (); chatpad.chatlinearea.setText ("Chesspadpad.connectServer Unable to connect / n" EC);}

} If (e.getSource () == controlpad.cancelGameButton) {if (isOnChess) {chesspad.chessthread.sendMessage ( "/ giveup" chessClientName); chesspad.chessVictory (-1 * chesspad.chessColor); controlpad.creatGameButton. setEnabled (true); controlpad.joinGameButton.setEnabled (true); controlpad.cancelGameButton.setEnabled (false); chesspad.statusText.setText ( "Please create a game or join a game");} if (! isOnChess) {controlpad.creatGameButton. setEnabled (true); controlpad.joinGameButton.setEnabled (true); controlpad.cancelGameButton.setEnabled (false); chesspad.statusText.setText ( "Please create a game or join a game");} isClient = isServer = false;}}

Public void keypressed (KeyEvent E) {textfield infutwords = (textfield) E.GETSOURCE ();

IF (E.GetKeycode () == keyevent.vk_enter) {if (InputPad.userchoice.getSelectedItem (). Equals ("owner") {Try {Out.writeutf (InputWords.getText ()); InputWords.Settext "");} CatCH (Exception EA) {chatpad.chatlinearea.setText ("ChessClient: keypressed unable to connect, suggest reconnection / N"); userpad.userlist.removell (); infutpad.userchoice.removeall (); inputs. setText ( ""); controlpad.connectButton.setEnabled (true);}} else {try {out.writeUTF ( "/" inputpad.userChoice.getSelectedItem () "" inputWords.getText ()); inputWords.setText ("");} Catch (Exception EA) {chatpad.chatlinearea.setText ("ChessClient: keypressed unable to connect, recommended reconnection / N"); userpad.userlist.removeall (); infutpad.userchoice.removeall (); InputWords .SETTEXT (""); controlpad.connectButton.setenabled (true);}}}}

Public void keytyped (keyevent E) {} public void keyreleased (keyevent e) {}

Public static void main (string args []) {chessclient chessclient = new chassclient ();}} / ***************************** *********************************************************** *********** The following is: chessinteface.java ****************************************** *********************************************************** ******** / Import java.awt. *; import java.awt.event. *; import java.io. *; import java.net. *;

Class Userpad Extends Panel {List UserList = New List (10);

Userpad () {setLayout (New BorderLayout ());

For (int i = 0; i <50; i ) {userlist.add (i "." "No User");} Add (userlist, borderlayout.center);

}

}

Class chatpad extends panel {textarea chatlinearea = new textarea ("", 18, 30, textarea.scrollbars_vertical_only); chatpad () {setLayout (new borderLayout ());

Add (chatlinearea, borderlayout.center);

}

class controlPad extends Panel {Label IPlabel = new Label ( "IP", Label.LEFT); TextField inputIP = new TextField ( "localhost", 10); Button connectButton = new Button ( "host connector"); Button creatGameButton = new Button ("Establishing Games"); Button JoingameButton = New Button ("Add to Game"); Button CancelGameButton = New Button ("Abandon Game"); Button ExitgameButton = New Button; "Close Program");

ControlPad () {setLayout (new flowLayout (FlowLayout.Left); setbackground (color.pink);

Add (IPLABEL); add (connectButton); add (creatgamebutton); add (joingamebutton); add (cangameButton); add (exitgamebutton);}

}

Class InputPad Extends Panel {TextField InputWords = New Textfield ("", 40); Choice Userchoice = New Choice ();

Inputpad () {setLayout (new flowLayout (FlowLayout.Left); for (int i = 0; i <50; i ) {userchoice.addItem (i " " No User ");} Userchoice.setsize (60 , 24); add (userchoice); add (inputword);}} / ************************************************** *********************************************************** *********** The following is: chesspad.java ******************************************* *********************************************************** *********** / Import java.awt. *; import java.awt.event. *; import java.io. *; import java.net. *; import java.util. *;

Class Chessthread Extends Thread {Chesspad Chesspad;

Chessthread (ChessPad Chesspad) {this.chesspad = chesspad;

public void sendMessage (String sndMessage) {try {chesspad.outData.writeUTF (sndMessage);} catch (Exception ea) {System.out.println ( "chessThread.sendMessage:" ea);}} public void acceptMessage (String recMessage ) {If (Recmessage.StartSwith ("/ chess")) {StringTokenizer UserToken = New StringTokenizer (Recmessage, ""); string chesstoken; string [] chessopt = {"- 1", "- 1", "0"} INT CHESSOPTNUM = 0;

While (useertoken.hasmoretoKens ()) {Chesstoken = (String) UserToken.nextToken (""); if (chessoptnum> = 1 && chessoptnum <= 3) {CHESSOPT [CHESSOPTNUM-1] = Chesstoken;

} Chessoptnum ;} chesspad.netchesspaint (Integer.Parseint (Chesopt [0]), Integer.Parseint (CHESSOPT [1]), Integer.Parseint (Chessopt [2]));

} Else if (recMessage.startsWith ( "/ yourname")) {chesspad.chessSelfName = recMessage.substring (10);} else if (recMessage.equals ( "/ error")) {chesspad.statusText.setText ( "Error: Without this user, please exit the program, re-join ");} else {//system.out.println (RecMessage);}}

Public void Run () {String Message = ""; try {while (true) {message = chesspad.indata.readutf (); acceptMessage (message);}} catch (ooException es)}}}

}

class chessPad extends Panel implements MouseListener, ActionListener {int chessPoint_x = -1, chessPoint_y = -1, chessColor = 1; int chessBlack_x [] = new int [200]; int chessBlack_y [] = new int [200]; int chessWhite_x [] = new int [200]; int chessWhite_y [] = int new [200]; int chessBlackCount = 0, chessWhiteCount = 0; int chessBlackWin = 0, chessWhiteWin = 0; boolean isMouseEnabled = false, isWin = false, isInGame = false; TextField STATUSTEXT = New TextField ("Please connect the server first,"

String chessselfname = null; string chesspeername = null; string host = null; int port = 4331; chessthread shssthread = new chessthread (this);

chessPad () {setSize (440,440); setLayout (null); setBackground (Color.pink); addMouseListener (this); add (statusText); statusText.setBounds (40,5,360,24); statusText.setEditable (false);}

public boolean connectServer (String ServerIP, int ServerPort) throws Exception {try {chessSocket = new Socket (ServerIP, ServerPort); inData = new DataInputStream (chessSocket.getInputStream ()); outData = new DataOutputStream (chessSocket.getOutputStream ()); chessthread .Start (); return true;} catch (ioException ex) {statustext.setText ("Chesspad: ConnectServer: Unable to connect / N");} Return False;}

Public void chessvictory (int Chesscolorwin) {this.removeall (); for (int i = 0; i <= chessblackcount; i ) {chessblack_x [i] = 0; chessblack_y [i] = 0;} for (INT i = 0 i <= chesswhitecount; i ) {chesswhite_x [i] = 0; chesswhite_y [i] = 0;} chessblackcount = 0; chesswhitecount = 0; add (statustext); statustext.setBounds (40, 5, 360, 24); IF Chesscolorwin == 1) {CHESSBLACKWIN ; statustext.settext ("Black Save, Black: White is" ChessBlackwin ":" ChessWhitewin ", re-opening, waiting in white and white ...);} else if (chesscolorwin = = -1) {CHESSWHITEWIN ; statustext.Settext ("White Square, Black: White is" ChessBlackwin ":" Chesswhitewin ", re-opening, waiting for black chess ...");}}

Public void getLocation (int A, int b, int color) {

if (color == 1) {chessBlack_x [chessBlackCount] = a * 20; chessBlack_y [chessBlackCount] = b * 20; chessBlackCount ;} else if (color == - 1) {chessWhite_x [chessWhiteCount] = a * 20; chessWhite_y [ Chesswhitecount] = B * 20; chesswhitecount ;}}

Public Boolean Checkwin (int A, int b, int checkcolor) {Int Step = 1, chesslink = 1, chesslinktest = 1, chesscompare = 0; if (checkcolor == 1) {CHESSLINK = 1; for (Step = 1; Step <= 4; Step ) {for (ChessCompare = 0; chesscompare <= chessblackcount; chesscompare ) {IF (((A Step) * 20 == ChessBlack_x [chesscompare]) && ((b * 20) == ChessBlack_y [chesscompare ])) {CHESSLINK = CHESSLINK 1; if (checklink == 5) {RETURN (TRUE);}}}}}}}}}}}}}}}}}) CHESSLINKTEST ; Else Break;} for (Step = 1; step; s <= 4; Step ) {for (checkcompare = 0; chesscompare <= chessblackcount; chesscompare ) {IF ((A-Step) * 20 == chessblack_x [chesscompare]) && (b * 20 == chessblack_y [chesscompare]) ) {CHESSLINK ; if (checklink == 5) {return (true);}}}}}}}}}}} f (chesslink == (CHESSLINKTEST 1)) CHESSLINKTEST ; else Break;} chesslink = 1; chesslinktest = 1; for (Step = 1 Step <= 4; step ) {for (chessCompare = 0; chessCompare <= chessBlackCount; chessCompare ) {if ((a * 20 == chessBlack_x [chessCompare]) && ((b step) * 20 == chessBlack_y [chessCompare])) {chessLink ; IF (chesslink == 5) {return (true);}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} f (chesslink ==)) CHESSLINKTEST ; else break;} for (step = 1; step <=

4; Step ) {for (chesscompare = 0; chesscompare <= chessblackcount; chesscompare ) {IF ((a * 20 == chessblack_x [chesscompare]) && ((b-step) * 20 == chessblack_y [chesscompare])) { Chesslink ; if (chesslink == 5) {Return (TRUE);}}}}}}}}}} f (checklinktest 1)) CHESSLINKTEST ; Else Break;} chesslink = 1; chesslinktest = 1; for (Step = 1; Step <= 4; Step ) {for (ChessCompare = 0; chesscompare <= chessblackcount; chesscompare ) {IF ((A-Step) * 20 == chessblack_x [chesscompare]) && ((B Step) * 20 == CHESSBLACK_Y [ChessCompare]) {CHESSLINK ; if (chesslink == 5) {return (true);}}}}}}}}}}}}}}}}}}}}}}}}) CHESSLINKTEST ; Else Break;} for (Step = 1; step <= 4; Step ) {for (chesscompare = 0; chesscompare <= chessblackcount; chesscompare ) {= ((A Step) * 20 == ChessBlack_x [chesscompare]) && ((b-step) * 2 0 == chessBlack_y [chessCompare])) {chessLink ; if (chessLink == 5) {return (true);}}} if (chessLink == (chessLinkTest 1)) chessLinkTest ; else break;} chessLink = 1; chessLinkTest = 1; for (step = 1; step <= 4; step ) {for (chesscompare = 0; chesscompare <= chessblackcount; chesscompare

) {IF * 20 == chessblack_x [chesscompare]) && ((B Step) * 20 == ChessBlack_y [chesscompare]) {CHESSLINK ; if (checklink == 5) {Return (True );}}} = (Checklinktest 1)) CHESSLINKTEST ; else break;} for (Step = 1; step <= 4; step ) {for (chesscompare = 0; chesscompare <= chessblackcount; chesscompare ) { IF ((A-Step) * 20 == CHESSBLACK_X [ChessCompare]) && (b-step) * 20 == chessblack_y [chesscompare]) {CHESSLINK ; if (chesslink == 5) {Return (TRUE); }}} F (CHESSLINK == (CHESSLINKTEST 1)) ChessLinkTest ; Else Break;}} else} else}} else} else}} else}} else}} else}} else}}} else}}} else}}} else} {CHESSLINK = 1; for (Step = 1; Step <= 4; Step ) {for (chesscompare = 0; chesscompare <= chesswhitecount; chesscompare ) {IF ((A Step) * 20 == Chesswhite_x [ChessCompare]) && (b * 20 == chesswhite_y [chesscompare])) { CHESSLINK ; if (checklink == 5) {return (true);}}}} (checklink ==)) ChessLinkTest ; else break;} for (Step = 1; step <= 4; step ) {for (chesscompare = 0; chesscompare <= chesswhitecount; chesscompare ) {IF ((A-Step) * 20 == chesswhite_x [chesscompare]) && (b * 20 == chesswhite_y [chesscompare]) {CHESSLINK

; If (checklink == 5) {return (true);}}}}}} (chesslink == (CHESSLINKTEST 1)) CHESSLINKTEST ; Else Break;} chesslink = 1; checklinktest = 1; for (Step = 1; Step <= 4; Step ) {for (chesscompare = 0; chesscompare <= chesswhitecount; chesscompare ) {IF ((a * 20 == chesswhite_x [chesscompare]) && ((B Step) * 20 == chesswhite_y [chesscompare]) ) {CHESSLINK ; if (chesslink == 5) {return (true);}}} f (checklink == (CHESSLINKTEST 1)) CHESSLINKTEST ; else break;} for (Step = 1; step <= 4; step ) {For (chesscompare = 0; chesscompare <= chesswhitecount; chesscompare ) {IF ((a * 20 == chesswhite_x [chesscompare]) && ((b-step) * 20 == chesswhite_y [chesscompare]) {CHESSLINK ; IF chessLink == 5) {return (true);}}} if (chessLink == (chessLinkTest 1)) chessLinkTest ; else break;} chessLink = 1; CHESSLINKTEST = 1; for (Step = 1; Step <= 4; Step ) {for (chesscompare = 0; chesscompare <= chesswhitecount; chesscompare ) {IF ((A-Step) * 20 == chesswhite_x [chesscompare]) && ((B Step) * 20 == ChessWhite_Y [ChessCompare]) {CHESSLINK ; if (checklink == 5) {return (true);}}}};

Else Break;} for (step = 1; step <= 4; step ) {for (chesscompare = 0; chesscompare <= chesswhitecount; chesscompare ) {IF (((A Step) * 20 == chesswhite_x [chesscompare]) && ((b-step) * 20 == chesswhite_y [chesscompare])) {CHESSLINK ; if (chesslink == 5) {return (true);}}}}}}}}}}}}}}}}}}; CHESSLINK = 1; chesslinktest = 1; for (Step = 1; step <= 4; step ) {for (chesscompare = 0; chesscompare <= chesswhitecount; chesscompare ) {IF (((A Step) * 20 == Chesswhite_x [ChessCompare]) && ((B Step) * 20 == ChessWhite_y [ChessCompare])) {CHESSLINK ; if (chesslink == 5) {return (true);}}}} (checklink == (CHESSLINKTEST 1 )) CHESSLINKTEST ; Else Break;} for (Step = 1; Step <= 4; Step ) {for (ChessCompare = 0; chesscompare <= chesswhitec Ount; chesscompare ) {IF ((a-step) * 20 == chesswhite_x [chesscompare]) && (b-step) * 20 == chesswhite_y [chesscompare]) {CHESSLINK ; if (chesslink == 5) { Return (True);}}} f (chesslink ==)) CHESSLINKTEST ; else break;}} return (false);

Public void Paint (GRAPHICS G) {for (int i = 40; i <= 380; i = i 20) {g.drawline (40, i, 400, i);} g.drawline (40, 400, 400, 400); for INT j = 40; j <= 380; j = j 20) {g.drawline (j, 40, j, 400);} g.drawline (400, 40, 400, 400); G.Filloval (97, 97, 6, 6); G. Filloval (337, 97, 6, 6); G. Filloval (97, 337, 6, 6); G. Filloval (337, 337, 6, 6); G. Filloval (217, 217, 6, 6); public void chessPaint (int chessPoint_a, int chessPoint_b, int color) {chessPoint_black chesspoint_black = new chessPoint_black (this); chessPoint_white chesspoint_white = new chessPoint_white (this);

if (color == 1 && isMouseEnabled) {getLocation (chessPoint_a, chessPoint_b, color); isWin = checkWin (chessPoint_a, chessPoint_b, color); if (isWin == false) {chessthread.sendMessage ( "/" chessPeerName "/ chess " chesspoint_a " chesspoint_b "" color); this.add (chesspoint_black); chesspoint_black.setbounds (checkpoint_a * 20-7, checkpoint_b * 20-7, 16, 16); statustext.settext ("Black (" Black (Pen " chessBlackCount "step)" chessPoint_a "" chessPoint_b ", please White lower sub"); isMouseEnabled = false;} else {chessthread.sendMessage ( "/" chessPeerName "/ chess" chessPoint_a "" chessPoint_b "" COLOR); this.add (checkpoint_black); chesspoint_black.setbounds (checkpoint_a * 20-7, checkpoint_b * 20-7, 16, 16); checkvictory (1); ismouseenabled = false;}} else == - 1 && ismouseenabled) {GetLocation (ChessPoint_a, ChessPoint_B, Color); Iswin = Checkwin (ChessPoint_a, ChessPoint_B, Color); if (iswin == false) {chessthread.sendMessage ("/" chesspee rName "/ chess" chessPoint_a "" chessPoint_b "" color); this.add (chesspoint_white); chesspoint_white.setBounds (chessPoint_a * 20-7, chessPoint_b * 20-7,16,16); statusText.setText ( " White (first " CHESSWHITECOUNT " 2 " chesspoint_a " chesspoint_b ", please black chess"); ismouseenabled = false;} else {chessthread.sendMessage ("/" chesspeern / chess "

ChessPoint_a "" chessPoint_b "" color); this.add (chesspoint_white); chesspoint_white.setBounds (chessPoint_a * 20-7, chessPoint_b * 20-7,16,16); chessVictory (-1); isMouseEnabled = false; }}} public void netChessPaint (int chessPoint_a, int chessPoint_b, int color) {chessPoint_black chesspoint_black = new chessPoint_black (this); chessPoint_white chesspoint_white = new chessPoint_white (this); getLocation (chessPoint_a, chessPoint_b, color); if (color == 1 ) {Iswin = checkwin (chesspoint_a, chesspoint_b, color); if (iswin == false) {

this.add (chesspoint_black); chesspoint_black.setBounds (chessPoint_a * 20-7, chessPoint_b * 20-7,16,16); statusText.setText ( "black (the" chessBlackCount "step)" chessPoint_a "" chessPoint_b " , Please, please "); ismouseEnabled = true;} else {this.add; chesspoint_black.setbounds (checkpoint_a * 20-7, chesspoint_b * 20-7, 16, 16); chessvictory (1); ismouseenabled = True;}} else if (color == - 1) {iswin = checkwin (chesspoint_a, chesspoint_b, color); if (iswin == false) {this.add (checkpoint_white); chesspoint_white.setbounds (checkpoint_a * 20-7, Chesspoint_b * 20-7, 16, 16); Statustext.Settext ("White (Part 10 CHESSWHITET " Step) " ChessPoint_a " ChessPoint_B ", please black chess"); ismouseenabled = true;} else {chessthread. sendMessage ( "/" chessPeerName "/ victory" color); this.add (chesspoint_white); chesspoint_white.setBounds (chessPoint_a * 20-7, chessPoint_b * 20-7,16,16); chessVictory (-1); isMouseEnabled = True;} }} Public void mousepressed (E.GETMODIFIERS () == INPUTEVENT.BUTTON1_MASK) {chesspoint_x = (int) E.GETX (); chesspoint_y = (int) E.GETY (); int a = Chesspoint_x 10) / 20, b = (CHESSPOINT_Y 10) / 20; if (ChessPoint_x / 20 <2 || chesspoint_y / 20 <2 || chesspoint_x / 20> 19 || chesspoint_y / 20> 19) {} else { Chesspaint (a, b, chesscolor);}}}

public void mouseReleased (MouseEvent e) {} public void mouseEntered (MouseEvent e) {} public void mouseExited (MouseEvent e) {} public void mouseClicked (MouseEvent e) {} public void actionPerformed (ActionEvent e) {

}

Class Chesspoint_Black Extends Canvas Implements MouseListener {Chesspad ChessPad = Null; ChessPoint_Black (ChessPadpad P) {setsize (20, 20); chesspad = p; addmouseristener (this);}

Public Void Paint (Graphics G) {g.setcolor (color.black); g.filloval (0,0,14,14);

Public void mousepressed (MouseEvent E) {// if (E.GETMODIFIERS () == INPUTEVENT.BUTTON3_MASK) // {// chesspad.remove (this); // chesspad.chesscolor = 1; // chesspad.text_2.setText (""); // chesspad.text_1.settext ("Please black chess"); //}} public void mousereleased (mouseEvent E) {} public void mouseentered (mouseEvent e) {} public void mouseexited (MouseEvent E) {} Public void mouseclicked (mouseevent e) {}}

Class ChessPoint_White Extends Canvas Implements MouseListener {Chesspad Chesspad = Null; ChessPoint_White (Chesspadpad P) {setsize (20, 20); addMouselistener (this); chesspad = p;}

Public void Paint (Graphics G) {g.setcolor (color.white); g.filloval (0,0,14,14);

Public void mousepressed (MouseEvent E) {// if (E.GETMODIFIERS () == INPUTEVENT.BUTTON3_MASK) // {// chesspad.remove (this); // chesspad.chesscolor = -1; // chesspad.text_2. SetText ("Please white flag"); // chesspad.text_1.settext (""); //}} public void mousereleased (mouseevent e) {} public void mouseentered (MouseEvent E) {} public void MouseExited (MouseEvent E) {} Public void mouseclicked (mouseEvent E) {// if (E.GetClickcount ()> = 2) // chesspad.remove (this);}} / ************** *********************************************************** ************************ Finally: chessserver.java *************************** *********************************************************** ********************** / Import java.io. *; import java.net. *; import java.awt. *; import java.util. * ; import java.awt.event *; class MessageServer extends Panel // implements ActionListener {TextArea messageBoard = new TextArea ( "", 22,50, TextArea.SCROLLBARS_VERTICAL_ONLY); Label statusLabel = new Label ( "current connections:.", Label.Left; panel boardpanel = new panel (); panel statusPanel = New PANEL ();

MessageServer () {setSize (350,300); setBackground (Color.pink); setLayout (new BorderLayout ()); boardPanel.setLayout (new FlowLayout ()); boardPanel.setSize (210,210); statusPanel.setLayout (new BorderLayout ()) StatusPanel.setsize (210, 50); BoardPanel.Add (Messageboard); StatusPanel.Add (StatusLabel, BorderLayout.West); add (BoardPanel, BorderLayout.Center); add (statuspanel, borderlayout.north);}}

Class ServerThread Extends Thread {Socket ClientSocket; Hashtable ClientDataHash; Hashtable ClientNameHash; Hashtable Chesspeerhash; Messageserver Server

Boolean isclientclosed = false;

ServerThread {this.clientSocket = clientSocket; this.clientDataHash = clientDataHash; this.clientNameHash = clientNameHash; this.chessPeerHash = chessPeerHash; this.server = server;} (Socket clientSocket, Hashtable clientDataHash, Hashtable clientNameHash, Hashtable chessPeerHash, MessageServer server) public Void MessageTransfer (String Message) {String ClientName, PeerName

IF (message.startswith) {

IF ("/ changename")) {ClientName = message.substring (12); if (ClientName.Length () <= 0 || ClientName.length ()> 20 || ClientName.StartSwith ("/" ) || clientNameHash.containsValue (clientName) || clientName.startsWith ( "changename") || clientName.startsWith ( "list") || clientName.startsWith ( "[inchess]") || clientName.startsWith ( "creatgame" || ClientName.StartSwith ("Joingame") || ClientName.StartSwith ("YourName") || ClientName.StartSwith ("UserList") || ClientName.StartSwith ("Chess") || ClientName.StartSwith ("OK" || ClientName.StartSwith ("Reject") || ClientName.StartSwith ("peer") || ClientName.StartSwith ("peername") || ClientName.StartSwith ("giveup") || ClientName.StartSwith ("Youwin" ) || ClientName.StartSwith ("owner") {message = "invalid command"; feedback (message);} else {if (ClientNameha sh.containsValue (( "[inchess]" (String) clientNameHash.get (clientSocket)))) {synchronized (clientNameHash) {clientNameHash.put ((Socket) getHashKey (clientNameHash, ( "[inchess]" clientNameHash.get ("[inchess" ("[inchess" clientname), ("/ YourName" ("[inchess" ("[inchess)) (" [inchess)))

}} Else if (chessPeerHash.containsKey (clientNameHash.get (clientSocket))) {// change the name of the game client synchronized (clientNameHash) {clientNameHash.put ((Socket) getHashKey (clientNameHash, ( "[inchess]" clientNameHash. get (clientSocket))), ( "[inchess]" clientName));} synchronized (chessPeerHash) {// chessPeerHash add new name mapping chessPeerHash.put (clientName, chessPeerHash.get (clientNameHash.get (clientSocket))); // chesspeerhash Removes the old mapping chesspeerhash.remove (ClientNameHash.Get);} // Send a new name Chesspertalk to the game client ("[inchess" ClientName, ("/ YourName" ("[inchess) ] " ClientName)))))))); / / Send Cheer Game Client Send Chesspertalk (" / Peer "[inchess]" clientname));

} Else if (chessPeerHash.containsValue (clientNameHash.get (clientSocket))) {synchronized (clientNameHash) {// change the name of the game client clientNameHash.put ((Socket) getHashKey (clientNameHash, ( "[inchess]" clientNameHash.get (clientSocket))), ( "[inchess]" clientName));} synchronized (chessPeerHash) {// chessPeerHash remapping chessPeerHash.put ((String) getHashKey (chessPeerHash, clientNameHash.get (clientSocket)), clientName); / / Send a new name Chesspertalk to the game client, ("/ YourName" ("[inchess" " ClientName)))))));} // Send CheerTalk to the Peer Game Client ( (String) GetHashKey (CHESSPEERHASH, ClientName), ("/ Peer" "[inchess" clientname);

}

message = clientNameHash.get (clientSocket) "renamed:" clientName; synchronized (clientNameHash) {clientNameHash.put (clientSocket, clientName);} publicTalk (message); Feedback ( "/ yourname" (String) clientNameHash.get (clientsocket); publictalk (getUserList ());}

} Else if ("/ List")) {feedback (incount, ("/ creatgame [inchess)) {string chessservername = message.substring (20); synchronized (clientNameHash) {clientNameHash.put (clientSocket, message.substring (11));} synchronized (chessPeerHash) {chessPeerHash.put (chessServerName, "wait");} Feedback ( "/ yourname" clientNameHash.get (clientSocket) ); chessPeerTalk (chessServerName, "/ OK"); publicTalk (getUserList ());} else if (message.startsWith ( "/ joingame")) {StringTokenizer userToken = new StringTokenizer (message, ""); String getUserToken, serverName , SelfName; String [] CHESSNAMEOPT = {"0", "0"}; int getoptnum = 0;

while (userToken.hasMoreTokens ()) {getUserToken = (String) userToken.nextToken ( ""); if (getOptNum> = 1 && getOptNum <= 2) {chessNameOpt [getOptNum-1] = getUserToken;} getOptNum ;} serverName = Chessnameopt [0]; SelfName = CHESSNAMEOPT [1];

if (chessPeerHash.containsKey (serverName) && chessPeerHash.get (serverName) .equals ( "wait")) {synchronized (clientNameHash) {clientNameHash.put (clientSocket, ( "[inchess]" selfName));} synchronized (chessPeerHash ) {CHESSPEERHASH.PUT (ServerName, SelfName);} publictalk ("/ peer" [inchess); cheername, ("/ peer"); checkpertalk ("/ peer" ("/ peer" " [inchess] "} else {chesspertalk (SelfName," / reject "); try {clientclose ();} catch (exception ez) {}}} else if (message.startswith (" / [inchess] ")) {INT firstLocation = 0, lastlocation; LastLocation = message.indexof (" ", 0);

Peername = message.substring ((FirstLocation 1), lastlocation; message = message.substring (LastLocation 1)); if (Cheername, Message)) {feedback ("/ error");}} else (message.startsWith ( "/ giveup")) {String chessClientName = message.substring (8);!. if (chessPeerHash.containsKey (chessClientName) && ((String) chessPeerHash.get (chessClientName)) equals ( "wait") ) {chessPeerTalk ((String) chessPeerHash.get (chessClientName), "/ youwin"); synchronized (chessPeerHash) {chessPeerHash.remove (chessClientName);}} if (chessPeerHash.containsValue (chessClientName)) {chessPeerTalk ((String) getHashKey (ChessClientName), "/ youwin"); synchronized (chesspeerhash) {chesspeerhash.remove (string) GetHashKey (ChessClientName));}}} else {

INT firstLocation; LastLocation; LastLocation = message.indexof ("", 0); if (LastLocation == - 1) {feedback ("invalid command"); return;} else {peername = message.substring ((FirstLocation 1), LastLocation; Message = Message.Substring (LastLocation 1)); Message = (String) ClientNameHash.Get (ClientSocket) "> Message; IF (Peername, Message) {feedback (" Without this user: " peername " / n ");}}

}

}

else {message = clientNameHash.get (clientSocket) ">" message; server.messageBoard.append (message "/ n"); publicTalk (message);. server.messageBoard.setCaretPosition (server.messageBoard.getText () length ());

}

Public void publictalk (String publicTalkMessage) {

synchronized (clientDataHash) {for (Enumeration enu = clientDataHash.elements (); enu.hasMoreElements ();) {DataOutputStream outData = (DataOutputStream) enu.nextElement (); try {outData.writeUTF (publicTalkMessage);} catch (IOException es ) {Es.printstacktrace ();}}}

}

Public Boolean Pertalk (String Peertalk, String TalkMessage) {

For (Enumeration ENU = ClientDataHash.keys (); ENU.haASMoreElements ();) {socket userclient = (socket) ENU.NEXTELEMENT ();

if (peerTalk.equals ((String) clientNameHash.get (userClient)) &&! peerTalk.equals ((String) clientNameHash.get (clientSocket))) {synchronized (clientDataHash) {DataOutputStream peerOutData = (DataOutputStream) clientDataHash.get (userClient ); try {peerOutData.writeUTF (talkMessage);} catch (IOException es) {es.printStackTrace ();}} Feedback (talkMessage); return (false);} else if (peerTalk.equals ((String) clientNameHash.get (ClientSocket)) {feedback (TalkMessage); Return (false);}} Return (TRUE);

}

Public Boolean Chesspertalk (String ChesstalkMessage) {

For (Enumeration ENU = ClientDataHash.keys (); ENU.haASMoreElements ();) {socket userclient = (socket) ENU.NEXTELEMENT ();

if (chessPeerTalk.equals ((String) clientNameHash.get (userClient)) &&! chessPeerTalk.equals ((String) clientNameHash.get (clientSocket))) {synchronized (clientDataHash) {DataOutputStream peerOutData = (DataOutputStream) clientDataHash.get (userClient ); Try {peeroutdata.writeutf (chesstalkMessage);} catch (ioException es) {es.printstacktrace ();}} return (false);}} Return (TRUE)

public void Feedback (String feedbackString) {synchronized (clientDataHash) {DataOutputStream outData = (DataOutputStream) clientDataHash.get (clientSocket); try {outData.writeUTF (feedbackString);} catch (Exception eb) {eb.printStackTrace ();}}

}

Public string getUserList () {string userlist = "/ userlist";

for (Enumeration enu = clientNameHash.elements (); enu.hasMoreElements ();) {userList = userList "" (String) enu.nextElement ();} return (userList);} 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 (havehkey) )) Return (hashkey);} return (null);

Public void firstcome () {publictalk (getUserList ()); feedback ("/ Yourname" (String) ClientNameHash.Get (ClientSocket)); Feedback ("Java Five Sports Chat Client"); feedback ("/ ChangeName - Change Name "); feedback (" / list - Update User List); feedback ("/ - private chat"); feedback ("Note: Use command Time, first set the object of the conversation as all people ");

public void clientClose () {server.messageBoard.append ( "OFF User:" clientSocket "/ n"); // if the game client host synchronized (chessPeerHash) {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) {clientDataHash.remove (clientSocket);} synchronized (clientNameHash) {clientNameHash.remove (clientSocket);} publicTalk (getUserList ()); server.statusLabel .SETTEXT ("Current Number of Connections:" ClientDataHash.size ()); Try {ClientSocket.close ();} catch (} catch (ooException exx) {}

Isclodclosed = true;

}

public void run () {DataInputStream inData; synchronized (clientDataHash) {server.statusLabel.setText ( "current number of connections:" clientDataHash.size ());} try {inData = new DataInputStream (clientSocket.getInputStream ()); firstCome (); While {string message = indata.readutf (); messagetransfer (message);}} catch (ooException esx) {} finally {if (! Isclodclosed) {ClientClose ();}}}}}}}

Public class chessserver extends frame imports anctionsListener {

Button MessageClearButton = New Button; Button ServerStatusButton = New Button; Button ServeroffButton = New Button ("Off Server"); Panel ButtonPanel = New Panel ();

MessageServer server = new MessageServer (); ServerSocket serverSocket; Hashtable clientDataHash = new Hashtable (50); Hashtable clientNameHash = new Hashtable (50); Hashtable chessPeerHash = new Hashtable (50);

Chessserver () {Super ("Java Give Chess Server"); SetBackground;

buttonPanel.setLayout (new FlowLayout ()); messageClearButton.setSize (60,25); buttonPanel.add (messageClearButton); messageClearButton.addActionListener (this); serverStatusButton.setSize (75,25); buttonPanel.add (serverStatusButton); serverStatusButton .addActionListener (this); ServeroffButton.setsize (75, 25); ButtonPanel.add (ServeroffButton); ServeroffButton.AddActionListener (this);

Add (BorderLayout.center); Add (ButtonPanel, BorderLayout.South);

AddWindowListener (new windowadapter () {applicationEvent e) {system.exit (0);}}); pack (); setvisible (true); setsize (400, 450); setResizable (false); validate (); TRY {makeMessageServer (4331, server);} catch (Exception e) {System.out.println ( "e");}} public void makeMessageServer (int port, MessageServer server) throws IOException {Socket clientSocket; long clientAccessNumber = 1; this .server = server;

Try {serversocket = new serversocket (port); server.Messageboard.Settext ("Server starts at:" ServerSocket.getinetaddress (). getLocalHost () ":" ServerSocket.getlocalPort () "/ n");

While (true) {clientsocket = serversocket.accept (); server.Messageboard.Append ("User Connection:" ClientSocket "/ N");

DataOutputStream Outdata = New DataOutputStream (ClientSocket.getOutputStream ());

ClientDatahash.Put (ClientSocket, Outdata); ClientNamehash.Put (ClientSocket, ("New Tour" ClientAccessNumber );

ServerThread thread = New ServerThread (ClientSocket, ClientDatahash, ClientNamehash, Chesspeerhash, Server);

Thread.start ();}} catch (ooException ex) {system.out.println ("already has a server in run. / n");}

}

public void actionPerformed (ActionEvent e) {if (e.getSource () == messageClearButton) {server.messageBoard.setText ( "");} if (e.getSource () == serverStatusButton) {try {server.messageBoard.append ("Server Information:" Serversocket.Getinetdress (). GetLocalHost () ":" ServerSocket.getlocalport () "/ n");} catch (Exception EE) {System.out.Println ("Serversocket.GetineTdRESS () .getlocalhost () error / n ");}} f (E.GetSource () == ServeroffButton) {system.exit (0);}} public static void main (string args []) {chessserver chessserver = new Chessserver ();}}

转载请注明原文地址:https://www.9cbs.com/read-94465.html

New Post(0)