Java網(wǎng)絡(luò)編程技術(shù)-08_第1頁
Java網(wǎng)絡(luò)編程技術(shù)-08_第2頁
Java網(wǎng)絡(luò)編程技術(shù)-08_第3頁
Java網(wǎng)絡(luò)編程技術(shù)-08_第4頁
Java網(wǎng)絡(luò)編程技術(shù)-08_第5頁
已閱讀5頁,還剩43頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

第8章JavaSocket網(wǎng)絡(luò)編程案例Java網(wǎng)絡(luò)五子棋程序設(shè)計(jì)28.1Java網(wǎng)絡(luò)五子棋需求分析1.應(yīng)用程序架構(gòu): Client/Server2.通信協(xié)議: TCP協(xié)議3.程序界面3

ServerClientClient48.2Server

HashtablekeyvalueclientDataHashSocketDataOutputStreamclientNameHashSochetclientNameclientPeerHashgameCreatorgameJoiner1〕集合

5publicclassFIRServerextendsFrameimplementsActionListener{JButtonclearMsgButton=newJButton("清空列表");JButtonserverStatusButton=newJButton("效勞器狀態(tài)");JButtoncloseServerButton=newJButton("關(guān)閉效勞器");PanelbuttonPanel=newPanel();ServerMsgPanelserverMsgPanel=newServerMsgPanel();ServerSocketserverSocket;HashtableclientDataHash=newHashtable(50);HashtableclientNameHash=newHashtable(50);HashtablechessPeerHash=newHashtable(50);publicFIRServer(){try{createServer(4331,serverMsgPanel);}catch(Exceptione){e.printStackTrace();}}2〕ServerClass6createServer()方法

publicvoidcreateServer(intport,ServerMsgPanelserverMsgPanel)throwsIOException{SocketclientSocket;longclientAccessNumber=1;this.serverMsgPanel=serverMsgPaneltry{

serverSocket=newServerSocket(port);while(true){

clientSocket=serverSocket.accept();

DataOutputStreamoutputData=newDataOutputStream(clientSocket.getOutputStream());clientDataHash.put(clientSocket,outputData);clientNameHash.put(clientSocket,("新玩家"

+clientAccessNumber++));

FIRServerThreadthread=newFIRServerThread(clientSocket,clientDataHash,clientNameHash,chessPeerHash,serverMsgPanel);

thread.start();}}catch(IOExceptionex){ex.printStackTrace();}}73〕FIRServerThreadClass

publicclassFIRServerThreadextendsThread{

SocketclientSocket;HashtableclientDataHash;HashtableclientNameHash;HashtablechessPeerHash;ServerMsgPanelserverMsgPanel;booleanisClientClosed=false;publicFIRServerThread(SocketclientSocket,HashtableclientDataHash,HashtableclientNameHash,HashtablechessPeerHash,

ServerMsgPanelserver){this.clientSocket=clientSocket;this.clientDataHash=clientDataHash;this.clientNameHash=clientNameHash;this.chessPeerHash=chessPeerHash;this.serverMsgPanel=server;}}8Feedback()方法publicvoidFeedback(StringfeedBackMsg){synchronized(clientDataHash){

DataOutputStreamoutputData=(DataOutputStream)

clientDataHash.get(clientSocket);try{outputData.writeUTF(feedBackMsg);}catch(Exceptioneb){eb.printStackTrace();}}}9sendGamePeerMsg()方法publicbooleansendGamePeerMsg(StringgamePeerTarget,StringgamePeerMsg){for(Enumerationenu=clientDataHash.keys();enu.hasMoreElements();){SocketuserClient=(Socket)enu.nextElement();if(gamePeerTarget.equals((String)clientNameHash.get(userClient))&&!gamePeerTarget.equals((String)clientNameHash.get(clientSocket))){synchronized(clientDataHash){DataOutputStreampeerOutData=(DataOutputStream)clientDataHash.get(userClient);try{peerOutData.writeUTF(gamePeerMsg);}catch(IOExceptiones){es.printStackTrace();}}returnfalse;}}returntrue;}10sendPublicMsg()方法publicvoidsendPublicMsg(StringpublicMsg){synchronized(clientDataHash){for(Enumerationenu=clientDataHash.elements();enu.hasMoreElements();){DataOutputStreamoutputData=(DataOutputStream)enu.nextElement();try{outputData.writeUTF(publicMsg);}catch(IOExceptiones){es.printStackTrace();}}}}11getUserList()方法publicStringgetUserList(){StringuserList="/userlist";for(Enumerationenu=clientNameHash.elements();enu.hasMoreElements();){userList=userList+""+(String)enu.nextElement();}returnuserList;}12getHashKey()方法publicObjectgetHashKey(HashtabletargetHash,ObjecthashValue){ObjecthashKey;for(Enumerationenu=targetHash.keys();enu.hasMoreElements();){hashKey=(Object)enu.nextElement();if(hashValue.equals((Object)targetHash.get(hashKey)))returnhashKey;}returnnull;}13sendInitMsg()方法publicvoidsendInitMsg(){sendPublicMsg(getUserList());Feedback("/yourname"+(String)clientNameHash.get(clientSocket));Feedback("Java五子棋客戶端");Feedback("/list--更新用戶列表");Feedback("/<username><talk>--私聊");Feedback("注意:命令必須對(duì)所有用戶發(fā)送");}14closeClient()方法publicvoidcloseClient(){serverMsgPanel.msgTextArea.append("用戶斷開連接:"

+clientSocket+"\n");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);}sendPublicMsg(getUserList());serverMsgPanel.statusLabel.setText("當(dāng)前連接數(shù):"

+clientDataHash.size());try{clientSocket.close();}catch(IOExceptionexx){exx.printStackTrace();}isClientClosed=true;}15run()方法publicvoidrun(){DataInputStreaminputData;synchronized(clientDataHash){serverMsgPanel.statusLabel.setText("當(dāng)前連接數(shù):"

+clientDataHash.size());}try{inputData=newDataInputStream(clientSocket.getInputStream());sendInitMsg();while(true){Stringmessage=inputData.readUTF();dealWithMsg(message);}}catch(IOExceptionesx){}finally{if(!isClientClosed){closeClient();}}}16dealWithMsg()方法publicvoiddealWithMsg(StringmsgReceived){StringclientName;StringpeerName;if(msgReceived.startsWith("/"))

{if(msgReceived.equals("/list"))

{Feedback(getUserList());}

elseif(msgReceived.startsWith("/creatgame[inchess]")){StringgameCreaterName=msgReceived.substring(20);synchronized(clientNameHash)

{

clientNameHash.put(clientSocket,msgReceived.substring(11));}synchronized(chessPeerHash)

{

chessPeerHash.put(gameCreaterName,"wait");}Feedback("/yourname"+clientNameHash.get(clientSocket));sendGamePeerMsg(gameCreaterName,"/OK");sendPublicMsg(getUserList());}17elseif(msgReceived.startsWith("/joingame")){StringTokenizeruserTokens=newStringTokenizer(msgReceived,"");StringuserToken;StringgameCreatorName;StringgamePaticipantName;String[]playerNames={"0","0"};intnameIndex=0;while(userTokens.hasMoreTokens()){userToken=(String)userTokens.nextToken("");if(nameIndex>=1&&nameIndex<=2){playerNames[nameIndex-1]=userToken;}nameIndex++;}gameCreatorName=playerNames[0];gamePaticipantName=playerNames[1];18if(chessPeerHash.containsKey(gameCreatorName)&&chessPeerHash.get(gameCreatorName).equals("wait")){synchronized(clientNameHash){clientNameHash.put(clientSocket,("[inchess]"+gamePaticipantName));}synchronized(chessPeerHash){chessPeerHash.put(gameCreatorName,gamePaticipantName);}sendPublicMsg(getUserList());sendGamePeerMsg(gamePaticipantName,("/peer"+"[inchess]"+gameCreatorName));sendGamePeerMsg(gameCreatorName,("/peer"+"[inchess]"+gamePaticipantName));}else{sendGamePeerMsg(gamePaticipantName,"/reject");try{closeClient();}catch(Exceptionez){ez.printStackTrace();}}}19elseif(msgReceived.startsWith("/[inchess]")){intfirstLocation=0,lastLocation;lastLocation=msgReceived.indexOf("",0);peerName=msgReceived.substring((firstLocation+1),lastLocation);msgReceived=msgReceived.substring((lastLocation+1));if(sendGamePeerMsg(peerName,msgReceived)){Feedback("/error");}}20elseif(msgReceived.startsWith("/giveup")){StringchessClientName=msgReceived.substring(8);

if(chessPeerHash.containsKey(chessClientName)&&!((String)chessPeerHash.get(chessClientName)).equals("wait")){sendGamePeerMsg((String)chessPeerHash.get(chessClientName),"/youwin");synchronized(chessPeerHash){chessPeerHash.remove(chessClientName);}}if(chessPeerHash.containsValue(chessClientName)){sendGamePeerMsg((String)getHashKey(chessPeerHash,chessClientName),"/youwin");synchronized(chessPeerHash){chessPeerHash.remove((String)getHashKey(chessPeerHash,chessClientName));}}}21else{intlastLocation=msgReceived.indexOf("",0);if(lastLocation==-1){Feedback("無效命令");return;}}22else{msgReceived=clientNameHash.get(clientSocket)+">"+msgReceived;serverMsgPanel.msgTextArea.append(msgReceived+"\n");sendPublicMsg(msgReceived);serverMsgPanel.msgTextArea.setCaretPosition(serverMsgPanel.msgTextArea.getText().length());}}8.3ClientpublicclassFIRClientextendsJFrameimplementsActionListener,KeyListener{SocketclientSocket;DataInputStreaminputStream;DataOutputStreamoutputStream;StringchessClientName=null;Stringhost=null;intport=4331;booleanisOnChat=false;//是否在聊天booleanisOnChess=false;//是否在下棋booleanisGameConnected=false;//游戲是否進(jìn)行中booleanisCreator=false;//是否為游戲創(chuàng)立者booleanisParticipant=false;//是否為游戲參加者UserListPaduserListPad=newUserListPad();//用戶列表區(qū)UserChatPaduserChatPad=newUserChatPad();//用戶聊天區(qū)23UserControlPaduserControlPad=newUserControlPad();//用戶操作區(qū)UserInputPaduserInputPad=newUserInputPad();//用戶輸入?yún)^(qū)FIRPadfirPad=newFIRPad();//下棋區(qū)PanelsouthPanel=newPanel();//面板區(qū)PanelnorthPanel=newPanel();PanelcenterPanel=newPanel();PaneleastPanel=newPanel();24publicFIRClient(){super("Java五子棋客戶端");setLayout(newBorderLayout());host=userControlPad.ipInputted.getText();eastPanel.setLayout(newBorderLayout());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);25userControlPad.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);26addWindowListener(newWindowAdapter(){publicvoidwindowClosing(WindowEvente){if(isOnChat){//聊天中try{//關(guān)閉客戶端套接口clientSocket.close();}catch(Exceptioned){}}if(isOnChess||isGameConnected){//下棋中try{//關(guān)閉下棋端口firPad.chessSocket.close();}catch(Exceptionee){}}System.exit(0);}});27add(eastPanel,BorderLayout.EAST);add(centerPanel,BorderLayout.CENTER);add(southPanel,BorderLayout.SOUTH);pack();setSize(670,560);setVisible(true);setResizable(false);this.validate();}28publicbooleanconnectToServer(StringserverIP,intserverPort)throwsException{try{clientSocket=newSocket(serverIP,serverPort);inputStream=newDataInputStream(clientSocket.getInputStream());outputStream=newDataOutputStream(clientSocket.getOutputStream());FIRClientThreadclientthread=newFIRClientThread(this);clientthread.start();isOnChat=true;returntrue;}catch(IOExceptionex){userChatPad.chatTextArea.setText("不能連接!\n");}returnfalse;}29publicvoidactionPerformed(ActionEvente){if(e.getSource()==userControlPad.connectButton){//連接到主機(jī)按鈕單擊事件host=firPad.host=userControlPad.ipInputted.getText();try{if(connectToServer(host,port)){userChatPad.chatTextArea.setText("");userControlPad.connectButton.setEnabled(false);userControlPad.createButton.setEnabled(true);userControlPad.joinButton.setEnabled(true);firPad.statusText.setText("連接成功,請(qǐng)等待!");}}catch(Exceptionei){userChatPad.chatTextArea.setText("不能連接!\n");}}30if(e.getSource()==userControlPad.exitButton){if(isOnChat){//假設(shè)用戶處于聊天狀態(tài)中try{//關(guān)閉客戶端套接口clientSocket.close();}catch(Exceptioned){}}if(isOnChess||isGameConnected){//假設(shè)用戶處于游戲狀態(tài)中try{//關(guān)閉游戲端口firPad.chessSocket.close();}catch(Exceptionee){}}System.exit(0);}31if(e.getSource()==userControlPad.joinButton){//參加游戲按鈕單擊事件StringselectedUser=(String)userListPad.userList.getSelectedItem();if(selectedUser==null||selectedUser.startsWith("[inchess]")||selectedUser.equals(chessClientName)){firPad.statusText.setText("必須選擇一個(gè)用戶!");}else{//執(zhí)行參加游戲的操作try{if(!isGameConnected){//假設(shè)游戲套接口未連接if(firPad.connectServer(firPad.host,firPad.port)){isGameConnected=true;isOnChess=true;isParticipant=true;userControlPad.createButton.setEnabled(false);userControlPad.joinButton.setEnabled(false);userControlPad.cancelButton.setEnabled(true);32firPad.firThread.sendMessage("/joingame"+(String)userListPad.userList.getSelectedItem()+""+chessClientName);}}else{//假設(shè)游戲端口連接中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(Exceptionee){isGameConnected=false;isOnChess=false;isParticipant=false;userControlPad.createButton.setEnabled(true);userControlPad.joinButton.setEnabled(true);userControlPad.cancelButton.setEnabled(false);userChatPad.chatTextArea.setText("不能連接:\n"+ee);}}}if(e.getSource()==userControlPad.createButton){try{if(!isGameConnected){//假設(shè)游戲端口未連接if(firPad.connectServer(firPad.host,firPad.port)){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{//假設(shè)游戲端口連接中isOnChess=true;isCreator=true;userControlPad.createButton.setEnabled(false);userControlPad.joinButton.setEnabled(false);userControlPad.cancelButton.setEnabled(true);34firPad.firThread.sendMessage("/creatgame"+"[inchess]"+chessClientName);}}catch(Exceptionec){isGameConnected=false;isOnChess=false;isCreator=false;userControlPad.createButton.setEnabled(true);userControlPad.joinButton.setEnabled(true);userControlPad.cancelButton.setEnabled(false);ec.printStackTrace();userChatPad.chatTextArea.setText("不能連接:\n”+ec);}}35if(e.getSource()==userControlPad.cancelButton){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("請(qǐng)創(chuàng)立或參加游戲!");}if(!isOnChess){//非游戲中userControlPad.createButton.setEnabled(true);userControlPad.joinButton.setEnabled(true);userControlPad.cancelButton.setEnabled(false);firPad.statusText.setText("請(qǐng)創(chuàng)立或參加游戲!");}isParticipant=isCreator=false;}}36publicvoidkeyPressed(KeyEvente){TextFieldinputwords=(TextField)e.getSource();if(e.getKeyCode()==KeyEvent.VK_ENTER){if(userInputPad.userChoice.getSelectedItem().equals("所有用戶")){//給所有人發(fā)信息try{//發(fā)送信息outputStream.writeUTF(inputwords.getText());inputwords.setText("");}catch(Exceptionea){userChatPad.chatTextArea.setText("不能連接到效勞器!\n");userListPad.userList.removeAll();userInputPad.userChoice.removeAll();inputwords.setText("");userControlPad.connectButton.setEnabled(true);}}else37{//給指定人發(fā)信息try{outputStream.writeUTF("/"+userInputPad.userChoice.getSelectedItem()+""+inputwords.getText());inputwords.setText("");}catch(Exceptionea){userChatPad.chatTextArea.setText("不能連接到效勞器!\n");userListPad.userList.removeAll();userInputPad.userChoice.removeAll();inputwords.setText("");userControlPad.connectButton.setEnabled(true);}}}}38publicvoidkeyTyped(KeyEvente){}publicvoidkeyReleased(KeyEvente){}publicstaticvoidmain(Stringargs[]){FIRClientchessClient=newFIRClient();}}398.4FIRClientThread類publicclassFIRClientThreadextendsThread{publicFIRClientfirClient;publicFIRClientThread(FIRClientfirClient){this.firClient=firClient;}40publicvoiddealWithMsg(StringmsgReceived){if(msgReceived.startsWith("/userlist")){StringTokenizeruserToken=newStringTokenizer(msgReceived,"");IntuserNumber=0;firClient.userListPad.userList.removeAll();firClient.userInputPad.userChoice.removeAll();firClient.userInputPad.userChoice.addItem("所有用戶");while(userToken.hasMoreTokens()){Stringuser=(String)userToken.nextToken("");if(userNumber>0&&!user.startsWith("[inchess]")){firClient.userListPad.userList.add(user);firClient.userInputPad.userChoice.addItem(user);}userNumber++;}firClient.userInputPad.userChoice.setSe

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論