




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
第8章JavaSocket網絡編程案例Java網絡五子棋程序設計28.1Java網絡五子棋需求分析1.應用程序架構: Client/Server2.通信協議: TCP協議3.程序界面3
ServerClientClient48.2Server
HashtablekeyvalueclientDataHashSocketDataOutputStreamclientNameHashSochetclientNameclientPeerHashgameCreatorgameJoiner1〕集合
5publicclassFIRServerextendsFrameimplementsActionListener{JButtonclearMsgButton=newJButton("清空列表");JButtonserverStatusButton=newJButton("效勞器狀態");JButtoncloseServerButton=newJButton("關閉效勞器");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("注意:命令必須對所有用戶發送");}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("當前連接數:"
+clientDataHash.size());try{clientSocket.close();}catch(IOExceptionexx){exx.printStackTrace();}isClientClosed=true;}15run()方法publicvoidrun(){DataInputStreaminputData;synchronized(clientDataHash){serverMsgPanel.statusLabel.setText("當前連接數:"
+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;//游戲是否進行中booleanisCreator=false;//是否為游戲創立者booleanisParticipant=false;//是否為游戲參加者UserListPaduserListPad=newUserListPad();//用戶列表區UserChatPaduserChatPad=newUserChatPad();//用戶聊天區23UserControlPaduserControlPad=newUserControlPad();//用戶操作區UserInputPaduserInputPad=newUserInputPad();//用戶輸入區FIRPadfirPad=newFIRPad();//下棋區PanelsouthPanel=newPanel();//面板區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{//關閉客戶端套接口clientSocket.close();}catch(Exceptioned){}}if(isOnChess||isGameConnected){//下棋中try{//關閉下棋端口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){//連接到主機按鈕單擊事件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("連接成功,請等待!");}}catch(Exceptionei){userChatPad.chatTextArea.setText("不能連接!\n");}}30if(e.getSource()==userControlPad.exitButton){if(isOnChat){//假設用戶處于聊天狀態中try{//關閉客戶端套接口clientSocket.close();}catch(Exceptioned){}}if(isOnChess||isGameConnected){//假設用戶處于游戲狀態中try{//關閉游戲端口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("必須選擇一個用戶!");}else{//執行參加游戲的操作try{if(!isGameConnected){//假設游戲套接口未連接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{//假設游戲端口連接中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){//假設游戲端口未連接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{//假設游戲端口連接中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("請創立或參加游戲!");}if(!isOnChess){//非游戲中userControlPad.createButton.setEnabled(true);userControlPad.joinButton.setEnabled(true);userControlPad.cancelButton.setEnabled(false);firPad.statusText.setText("請創立或參加游戲!");}isParticipant=isCreator=false;}}36publicvoidkeyPressed(KeyEvente){TextFieldinputwords=(TextField)e.getSource();if(e.getKeyCode()==KeyEvent.VK_ENTER){if(userInputPad.userChoice.getSelectedItem().equals("所有用戶")){//給所有人發信息try{//發送信息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{//給指定人發信息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等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 園林亮化施工方案范本
- 石家莊地面防腐施工方案
- 寧夏職業技術學院《歐美文學史AⅡ》2023-2024學年第二學期期末試卷
- 江西科技職業學院《藥用植物與生藥學》2023-2024學年第二學期期末試卷
- 浙江音樂學院《水利工程概預算》2023-2024學年第二學期期末試卷
- 南京工業職業技術大學《化工制圖與AutoCAD》2023-2024學年第二學期期末試卷
- 漳州職業技術學院《PLC與電氣控制》2023-2024學年第二學期期末試卷
- 2025至2031年中國毛刷膠輥行業投資前景及策略咨詢研究報告
- 內蒙古工業大學《電子商務雙語》2023-2024學年第二學期期末試卷
- 城鎮道路基礎施工方案
- 梁思成《千篇一律與千變萬化》(課件)
- 泵車作業安全協議書
- 智能汽車傳感器技術-激光雷達
- 武漢市建設工程施工合同管理辦法暫行
- 急救醫藥箱藥品清單
- 突發性聾診療指南
- 南方少數民族傳統合唱精講智慧樹知到答案章節測試2023年四川音樂學院
- 35kv電纜敷設施工方案正式版
- 漁家傲(天接云濤連曉霧)說課稿
- GB/T 3098.26-2021緊固件機械性能平墊圈
- GB/T 30220-2013游樂設施安全使用管理
評論
0/150
提交評論