码迷,mamicode.com
首页 > 其他好文 > 详细

实验楼第三次试验报告

时间:2015-06-05 06:12:27      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

实验楼第三次试验报告

北京电子科技学院(BESTI

              

课程:Java程序设计  班级:1353  姓名:李雪琦  学号:20135309

成绩:               指导教师:娄嘉鹏     实验日期:2015.6.4

实验密级:      预习程度:        实验时间:

仪器组次:      必修/选修:选修     实验序号:3

实验名称:             Java敏捷开发XP实践                                               

实验内容:

1. XP基础

2. XP核心实践

3. 相关工具 

实验仪器:

名称

型号

数量

PC

 Lenovo

1

虚拟机

实验楼

1

 实验步骤:

 (一)敏捷开发与XP:

常见的开发流程有:

  • RUP(Rational Unified Process)
  • PSP(Personal Software Process )
  • TSP(Team Software Process )
  • Agile Process
  • ……

敏捷开发(Agile Development)是一种以人为核心、迭代、循序渐进的开发方法。其中,极限编程(eXtreme Programming,XP)是一种全新而快捷的软件开发方法。

  • XP是以开发符合客户需要的软件为目标而产生的一种方法论
  • XP是一种以实践为基础的软件工程过程和思想
  • XP认为代码质量的重要程度超出人们一般所认为的程度
  • XP特别适合于小型的有责任心的、自觉自励的团队开发需求不确定或者迅速变化的软件

XP软件开发是什么样的通过 XP准则来表达:

  • 沟通 :XP认为项目成员之间的沟通是项目成功的关键,并把沟通看作项目中间协调与合作的主要推动因素。
  • 简单 :XP假定未来不能可靠地预测,在现在考虑它从经济上是不明智的,所以不应该过多考虑未来的问题而是应该集中力量解决燃眉之急。
  • 反馈 :XP认为系统本身及其代码是报告系统开发进度和状态的可靠依据。系统开发状态的反馈可以作为一种确定系统开发进度和决定系统下一步开发方向的手段。
  • 勇气:代表了XP认为人是软件开发中最重要的一个方面的观点。在一个软件产品的开发中人的参与贯穿其整个生命周期,是人的勇气来排除困境,让团队把局部的最优抛之脑后,达到更重大的目标。表明了XP对“人让项目取得成功”的基本信任态度。

一项实践在XP环境中成功使用的依据通过XP的法则呈现,包括:快速反馈、假设简单性、递增更改、提倡更改、优质工作。

XP软件开发的基石是XP的活动,包括:编码、测试、倾听、设计。

 

(二)编码标准

单击Eclipse菜单中的source->Format 或用快捷键Ctrl+Shift+F就可以按Eclipse规定的规范缩进

Java中的一般的命名规则有:

  • 要体现各自的含义
  • 包、类、变量用名词
  • 方法名用动宾
  • 包名全部小写,如:io,awt
  • 类名第一个字母要大写,如:HelloWorldApp
  • 变量名第一个字母要小写,如:userName
  • 方法名第一个字母要小写:setName
  • ...

标识符名字应当直观且可以拼读,可望文知意,不必进行“解码”,一般采用英文单词或其组合,便于记忆和阅读。 

代码标准:七个原则

不要预先花费太多时间

目标应该是团队中没有人辨认各自的代码

以团队为单位对某一标准达成协议,然后遵守这一标准

不是事无巨细的规则列表,而是去本报代码可交流的指导方针

编码标准开始时应该很简单,然后根据团队经验逐步优化

创建能够工作的最简单标准,然后逐步发展

只制定适合本团队的

 

 技术分享

 

 

(三)结对编程

结对编程是XP中的重要实践。在结对编程模式下,一对程序员肩并肩、平等地、互补地进行开发工作。

驾驶员(Driver)是控制键盘输入的人。

领航员(Navigator)起到领航、提醒的作用。

 

•     驾驶员:写设计文档,进行编码和单元测试等XP开发流程。

•     领航员:审阅驾驶员的文档、驾驶员对编码等开发流程的执行;考虑单元测试的覆盖率;思考是否需要和如何重构;帮助驾驶员解决具体的技术问题。

•     驾驶员和领航员不断轮换角色,不要连续工作超过一小时,每工作一小时休息15分钟。领航员要控制时间。

•     主动参与。任何一个任务都首先是两个人的责任,也是所有人的责任。没有“我的代码”、“你的代码”或“他/她的代码”,只有“我们的代码”。

•     只有水平上的差距,没有级别上的差异。两人结对,尽管可能大家的级别资历不同,但不管在分析、设计或编码上,双方都拥有平等的决策权利。

(四)版本控制

我的代码库:http://git.shiyanlou.com/20135309

1、好处

•       版本控制提供项目级的 undo(撤销) 功能: 没有什么事情是终结版本, 任何错误必须很容易回滚。 假设你在使用世界上最复杂的文字处理系统。 它具备了所有的能想到的功能,就是没有支持 DELETE(删除) 键。想象你打字的时候得多么的谨慎和缓慢吧, 特别是一篇超大的文档的快临近末尾的时候, 一个不小心就要重头再来(试想你选中所有的文字, 不小心按了 DELETE 键, 因为没有撤销功能,只好重新录入)。编辑文字和版本控制相同,任何时候都需要回滚,无论是一个小时, 一天, 还是一周, 这让你的团队工作自由快速的工作, 而且对于修正错误也非常自信。

•       版本控制允许多人在同一代码上工作, 只要遵守一定的控制原则就行。 再也不会发生诸如一个人覆盖了另一个人编辑的代码,导致那个人的修改无效这样的情况。

•       版本控制系统保存了过去所作的修改的历史记录。如果你遭遇到一些惊讶的代码,通过版本控制系统可以很容易找出是谁干的, 修改了什么, 修改的时间, 如果幸运的话,还能找出原因。

•       版本控制系统还支持在主线上开发的同时发布多个软件版本。在软件发布的时候也不需要整个团队的停止工作,不需要冻结代码。

•       版本控制也是项目级的时间机器,你可以选择任何一个时间, 精  确地查看项目在当时的情况。 这对研究非常有用, 也是重现以前某个有问题的发布版本的基础。

举例:Hello World.java

 技术分享

 技术分享

 

 技术分享

 

(五)重构:

         重构(Refactor),就是在不改变软件外部行为的基础上,改变软件内部的结构,使其更加易于阅读、易于维护和易于变更. 

一个完整的重构流程包括:

1.      从版本控制系统代码库中Check out code

2.      读懂代码(包括测试代码)

3.      发现bad smell

4.      Refactoring

5.      运行所有的Unit Tests

6.      往代码库中Check in code

 技术分享

 技术分享

(六)结对项目

 技术分享

 技术分享

技术分享

源代码:

1、chessClient.java

package wuziqi2;

 

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.net.*;

import java.util.*;

 

 

class clientThread extends Thread

{

 chessClient chessclient;

 

 clientThread(chessClient chessclient)

 {

  this.chessclient=chessclient;

 }

 

 public void acceptMessage(String recMessage)

 {

  if(recMessage.startsWith("/userlist "))

  {

   StringTokenizer userToken=new StringTokenizer(recMessage," ");

   int userNumber=0;

 

   chessclient.userpad.userList.removeAll();

   chessclient.inputpad.userChoice.removeAll();

   chessclient.inputpad.userChoice.addItem("所有人");

   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("所有人");

  }

  else if(recMessage.startsWith("/yourname "))

  {

   chessclient.chessClientName=recMessage.substring(10);

   chessclient.setTitle("Java五子棋客户端   "+"用户名:"+chessclient.chessClientName);

  }

  else if(recMessage.equals("/reject"))

  {

   try

   {

    chessclient.chesspad.statusText.setText("不能加入游戏");

    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无法关闭");

   }

   chessclient.controlpad.joinGameButton.setEnabled(true);

  }

  else if(recMessage.startsWith("/peer "))

  {

   chessclient.chesspad.chessPeerName=recMessage.substring(6);

   if(chessclient.isServer)

   {

    chessclient.chesspad.chessColor=1;

    chessclient.chesspad.isMouseEnabled=true;

    chessclient.chesspad.statusText.setText("请黑棋下子");

   }

   else if(chessclient.isClient)

   {

    chessclient.chesspad.chessColor=-1;

    chessclient.chesspad.statusText.setText("已加入游戏,等待对方下子...");

   }

 

  }

  else if(recMessage.equals("/youwin"))

  {

   chessclient.isOnChess=false;

   chessclient.chesspad.chessVictory(chessclient.chesspad.chessColor);

   chessclient.chesspad.statusText.setText("对方退出,请点放弃游戏退出连接");

   chessclient.chesspad.isMouseEnabled=false;

  }

  else if(recMessage.equals("/OK"))

  {

   chessclient.chesspad.statusText.setText("创建游戏成功,等待别人加入...");

  }

  else if(recMessage.equals("/error"))

  {

   chessclient.chatpad.chatLineArea.append("传输错误:请退出程序,重新加入 \n");

  }

  else

  {

   chessclient.chatpad.chatLineArea.append(recMessage+"\n");

   chessclient.chatpad.chatLineArea.setCaretPosition(

    chessclient.chatpad.chatLineArea.getText().length());

  }

 }

 

 

 public void run()

 {

     String message="";

     try

     {

   while(true)

   {

    message=chessclient.in.readUTF();

    acceptMessage(message);

   }

  }

  catch(IOException 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;

 DataInputStream in;

 DataOutputStream out;

 String chessClientName=null;

 String host=null;

 int port=4331;

 

 boolean isOnChat=false;  //在聊天?

 boolean isOnChess=false; //在下棋?

 boolean isGameConnected=false; //下棋的客户端连接?

 boolean isServer=false; //如果是下棋的主机

 boolean isClient=false; //如果是下棋的客户端

 

 Panel southPanel=new Panel();

 Panel northPanel=new Panel();

 Panel centerPanel=new Panel();

 Panel westPanel=new Panel();

 Panel eastPanel=new Panel();

 

 chessClient()

 {

  super("Java五子棋客户端");

  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(Color.pink);

 

 

  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:无法连接,建议重新启动程序 \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("连接成功,请创建游戏或加入游戏");

     }

 

 

    }

    catch(Exception ei)

    {

     chatpad.chatLineArea.setText("controlpad.connectButton:无法连接,建议重新启动程序 \n");

    }

    }

    if(e.getSource()==controlpad.exitGameButton)

    {

     if(isOnChat)

     {

      try

      {

       chatSocket.close();

      }

      catch(Exception ed)

      {

      }

     }

     if(isOnChess || isGameConnected)

     {

      try

      {

       chesspad.chessSocket.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("必须先选定一个有效用户");

     }

     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.setEnabled(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无法连接 \n"+ee);

      }

 

     }

    }

    if(e.getSource()==controlpad.creatGameButton)

    {

     try

     {

      if(!isGameConnected)

      {

       if(chesspad.connectServer(chesspad.host,chesspad.port))

       {

        isGameConnected=true;

        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.joinGameButton.setEnabled(true);

      controlpad.cancelGameButton.setEnabled(false);

      ec.printStackTrace();

      chatpad.chatLineArea.setText("chesspad.connectServer无法连接 \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("请建立游戏或者加入游戏");

     }

     if(!isOnChess)

     {

      controlpad.creatGameButton.setEnabled(true);

      controlpad.joinGameButton.setEnabled(true);

      controlpad.cancelGameButton.setEnabled(false);

      chesspad.statusText.setText("请建立游戏或者加入游戏");

     }

     isClient=isServer=false;

     }

 

   }

 

 

 

   public void keyPressed(KeyEvent e)

   {

    TextField inputWords=(TextField)e.getSource();

 

 

    if(e.getKeyCode()==KeyEvent.VK_ENTER)

    {

     if(inputpad.userChoice.getSelectedItem().equals("所有人"))

     {

      try

      {

       out.writeUTF(inputWords.getText());

       inputWords.setText("");

      }

      catch(Exception ea)

      {

       chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接 \n");

       userpad.userList.removeAll();

       inputpad.userChoice.removeAll();

       inputWords.setText("");

       controlpad.connectButton.setEnabled(true);

      }

     }

     else

     {

      try

      {

       out.writeUTF("/"+inputpad.userChoice.getSelectedItem()+" "+inputWords.getText());

       inputWords.setText("");

      }

      catch(Exception ea)

      {

       chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接 \n");

       userpad.userList.removeAll();

       inputpad.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 chessClient();

   }

}

2、chessInteface.java

package wuziqi2;

 

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+"."+"没有用户");

  }

  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("连接主机");

 Button creatGameButton=new Button("建立游戏");

 Button joinGameButton=new Button("加入游戏");

 Button cancelGameButton=new Button("放弃游戏");

 Button exitGameButton=new Button("关闭程序");

 

 controlPad()

 {

  setLayout(new FlowLayout(FlowLayout.LEFT));

        setBackground(Color.pink);

 

  add(IPlabel);

  add(inputIP);

  add(connectButton);

  add(creatGameButton);

  add(joinGameButton);

  add(cancelGameButton);

  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+"."+"没有用户");

  }

  userChoice.setSize(60,24);

  add(userChoice);

  add(inputWords);

 }

}

3、chessPad.java

package wuziqi2;

 

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(userToken.hasMoreTokens())

   {

    chessToken=(String)userToken.nextToken(" ");

    if(chessOptNum>=1 && chessOptNum<=3)

    {

     chessOpt[chessOptNum-1]=chessToken;

 

    }

    chessOptNum++;

   }

   chesspad.netChessPaint(Integer.parseInt(chessOpt[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("错误:没有这个用户,请退出程序,重新加入");

  }

  else

  {

   //System.out.println(recMessage);

  }

 }

 

 

 public void run()

 {

     String message="";

     try

     {

   while(true)

   {

    message=chesspad.inData.readUTF();

    acceptMessage(message);

   }

  }

  catch(IOException 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[]=new int[200];

 int chessBlackCount=0,chessWhiteCount=0;

 int chessBlackWin=0,chessWhiteWin=0;

 boolean isMouseEnabled=false,isWin=false,isInGame=false;

 TextField statusText=new TextField("请先连接服务器");

 

    Socket chessSocket;

 DataInputStream inData;

 DataOutputStream outData;

 

 String chessSelfName=null;

 String chessPeerName=null;

 String host=null;

 int port=4331;

 chessThread chessthread=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:无法连接 \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("黑棋胜,黑:白为"+chessBlackWin+":"+chessWhiteWin+",重新开局,等待白棋下子...");

   }

      else if(chessColorWin==-1)

      {

    chessWhiteWin++;

    statusText.setText("白棋胜,黑:白为"+chessBlackWin+":"+chessWhiteWin+",重新开局,等待黑棋下子...");

   }

  }

 

 

 

     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(chessLink==5)

       {

        return(true);

       }

      }

      }

      if(chessLink==(chessLinkTest+1))

      chessLinkTest++;

      else

      break;

     }

    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++;

       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((a*20==chessBlack_x[chessCompare]) && ((b+step)*20==chessBlack_y[chessCompare]))

      {

       chessLink++;

       if(chessLink==5)

       {

        return(true);

       }

       }

         }

         if(chessLink==(chessLinkTest+1))

         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);

       }

       }

      }

      if(chessLink==(chessLinkTest+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);

        }

         }

     }

     if(chessLink==(chessLinkTest+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);

        }

         }

        }

        if(chessLink==(chessLinkTest+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);

        }

         }

        }

        if(chessLink==(chessLinkTest+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);

          }

      }

     }

        if(chessLink==(chessLinkTest+1))

        chessLinkTest++;

        else

        break;

       }

   }

     else if(checkColor==-1)

     {

    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(chessLink==5)

       {

        return(true);

       }

       }

      }

      if(chessLink==(chessLinkTest+1))

      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(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*20==chessWhite_x[chessCompare]) && ((b+step)*20==chessWhite_y[chessCompare]))

      {

       chessLink++;

       if(chessLink==5)

       {

        return(true);

       }

       }

      }

      if(chessLink==(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(chessLink==5)

       {

        return(true);

       }

       }

      }

      if(chessLink==(chessLinkTest+1))

      chessLinkTest++;

      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);

       }

         }

        }

        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(chessLink==5)

         {

          return(true);

          }

       }

      }

      if(chessLink==(chessLinkTest+1))

      chessLinkTest++;

      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);

          }

         }

      }

      if(chessLink==(chessLinkTest+1))

      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(chessPoint_a*20-7,chessPoint_b*20-7,16,16);

      statusText.setText("黑(第"+chessBlackCount+"步)"+chessPoint_a+" "+chessPoint_b+",请白棋下子");

      isMouseEnabled=false;

     }

     else

     {

      chessthread.sendMessage("/"+chessPeerName+" /chess "+chessPoint_a+" "+chessPoint_b+" "+color);

      this.add(chesspoint_black);

      chesspoint_black.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16);

      chessVictory(1);

      isMouseEnabled=false;

     }

    }

    else 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_white);

      chesspoint_white.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16);

      statusText.setText("白(第"+chessWhiteCount+"步)"+chessPoint_a+" "+chessPoint_b+",请黑棋下子");

      isMouseEnabled=false;

     }

     else

     {

      chessthread.sendMessage("/"+chessPeerName+" /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("黑(第"+chessBlackCount+"步)"+chessPoint_a+" "+chessPoint_b+",请白棋下子");

      isMouseEnabled=true;

     }

     else

     {

      this.add(chesspoint_black);

      chesspoint_black.setBounds(chessPoint_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(chesspoint_white);

      chesspoint_white.setBounds(chessPoint_a*20-7,chessPoint_b*20-7,16,16);

      statusText.setText("白(第"+chessWhiteCount+"步)"+chessPoint_a+" "+chessPoint_b+",请黑棋下子");

      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(MouseEvent e)

      {

    if (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(chessPad p)

 {

  setSize(20,20);

  chesspad=p;

  addMouseListener(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("请黑棋下子");

//  }

 }

 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(chessPad 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("请白旗下子");

//   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);

 }

}

4、chessServer.java

package wuziqi2;

 

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("当前连接数:",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(Socket clientSocket,Hashtable clientDataHash,Hashtable clientNameHash,Hashtable chessPeerHash,MessageServer server)

 {

  this.clientSocket=clientSocket;

  this.clientDataHash=clientDataHash;

  this.clientNameHash=clientNameHash;

  this.chessPeerHash=chessPeerHash;

  this.server=server;

 }

 

 

 

 public void messageTransfer(String message)

 {

  String clientName,peerName;

 

  if(message.startsWith("/"))

  {

 

   if(message.startsWith("/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("所有人"))

    {

     message="无效命令";

     Feedback(message);

    }

    else

    {

     if(clientNameHash.containsValue(("[inchess]"+(String)clientNameHash.get(clientSocket))))

     {

      synchronized(clientNameHash)

      {

       clientNameHash.put((Socket)getHashKey(clientNameHash,("[inchess]"+clientNameHash.get(clientSocket))),

            ("[inchess]"+clientName));

       chessPeerTalk(("[inchess]"+clientName),("/yourname "+("[inchess]"+clientName)));

      }

     }

     else if(chessPeerHash.containsKey(clientNameHash.get(clientSocket)))

     {

      //游戏客户端改名字

      synchronized(clientNameHash)

      {

       clientNameHash.put((Socket)getHashKey(clientNameHash,("[inchess]"+clientNameHash.get(clientSocket))),

            ("[inchess]"+clientName));

      }

 

      synchronized(chessPeerHash)

      {

       //chessPeerHash添加新名字映射

       chessPeerHash.put(clientName,chessPeerHash.get(clientNameHash.get(clientSocket)));

       //chessPeerHash删除旧映射

       chessPeerHash.remove(clientNameHash.get(clientSocket));

      }

      //向游戏客户端发送新名字

      chessPeerTalk(("[inchess]"+clientName),("/yourname "+("[inchess]"+clientName)));

      //向peer游戏客户端发送

      chessPeerTalk((String)chessPeerHash.get(clientName),("/peer "+"[inchess]"+clientName));

 

     }

     else if(chessPeerHash.containsValue(clientNameHash.get(clientSocket)))

     {

      synchronized(clientNameHash)

      {

       //游戏客户端改名字

       clientNameHash.put((Socket)getHashKey(clientNameHash,("[inchess]"+clientNameHash.get(clientSocket))),

                  ("[inchess]"+clientName));

      }

      synchronized(chessPeerHash)

      {

       //chessPeerHash重新映射

       chessPeerHash.put((String)getHashKey(chessPeerHash,clientNameHash.get(clientSocket)),clientName);

       //向游戏客户端发送新名字

       chessPeerTalk(("[inchess]"+clientName),("/yourname "+("[inchess]"+clientName)));

      }

      //向peer游戏客户端发送

      chessPeerTalk((String)getHashKey(chessPeerHash,clientName),("/peer "+"[inchess]"+clientName));

 

     }

 

     message=clientNameHash.get(clientSocket)+"改名为:"+clientName;

     synchronized(clientNameHash)

     {

      clientNameHash.put(clientSocket,clientName);

     }

     publicTalk(message);

     Feedback("/yourname "+(String)clientNameHash.get(clientSocket));

     publicTalk(getUserList());

 

    }

 

   }

   else if(message.equals("/list"))

   {

    Feedback(getUserList());

          }

          else if(message.startsWith("/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(getUserList());

     chessPeerTalk(selfName,("/peer "+"[inchess]"+serverName));

     chessPeerTalk(serverName,("/peer "+"[inchess]"+selfName));

    }

    else

    {

     chessPeerTalk(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(chessPeerTalk(peerName,message))

    {

     Feedback("/error");

    }

   }

   else if(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(chessPeerHash,chessClientName),"/youwin");

     synchronized(chessPeerHash)

     {

      chessPeerHash.remove((String)getHashKey(chessPeerHash,chessClientName));

     }

    }

   }

   else

   {

 

    int firstLocation=0,lastLocation;

 

                lastLocation=message.indexOf(" ",0);

    if(lastLocation==-1)

    {

     Feedback("无效命令");

     return;

    }

    else

    {

     peerName=message.substring((firstLocation+1),lastLocation);

     message=message.substring((lastLocation+1));

     message=(String)clientNameHash.get(clientSocket)+">"+message;

     if(peerTalk(peerName,message))

     {

      Feedback("没有这个用户:"+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 peerTalk(String peerTalk,String talkMessage)

    {

 

        for(Enumeration enu=clientDataHash.keys();enu.hasMoreElements();)

        {

   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 chessPeerTalk(String chessPeerTalk,String chessTalkMessage)

    {

 

        for(Enumeration enu=clientDataHash.keys();enu.hasMoreElements();)

        {

   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(hashKey)))

    return(hashKey);

     }

     return(null);

 }

 

 public void firstCome()

 {

  publicTalk(getUserList());

  Feedback("/yourname "+(String)clientNameHash.get(clientSocket));

  Feedback("Java五子棋聊天客户端");

  Feedback("/changename <你的名字>  --更改名字");

  Feedback("/list --更新用户列表");

  Feedback("/<用户名> <要说的话>  --私聊");

  Feedback("注意:用命令的时候,先把谈话的对象定为所有人");

 }

 

 

 

 public void clientClose()

 {

  server.messageBoard.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);

  }

  publicTalk(getUserList());

  server.statusLabel.setText("当前连接数:"+clientDataHash.size());

  try

  {

   clientSocket.close();

  }

  catch(IOException exx)

  {

  }

 

  isClientClosed=true;

 

 }

 

 

 public void run()

 {

  DataInputStream inData;

        synchronized(clientDataHash)

        {

   server.statusLabel.setText("当前连接数:"+clientDataHash.size());

  }

  try

  {

   inData=new DataInputStream(clientSocket.getInputStream());

            firstCome();

   while(true)

   {

    String message=inData.readUTF();

    messageTransfer(message);

   }

  }

  catch(IOException esx)

  {

  }

  finally

  {

   if(!isClientClosed)

   {

    clientClose();

   }

  }

 }

 

 

}

 

 

 

 

 

 

public class chessServer extends Frame implements ActionListener

{

 

 Button messageClearButton=new Button("清除显示");

 Button serverStatusButton=new Button("服务器状态");

 Button serverOffButton=new Button("关闭服务器");

 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五子棋服务器");

  setBackground(Color.pink);

 

 

  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(server,BorderLayout.CENTER);

  add(buttonPanel,BorderLayout.SOUTH);

 

  addWindowListener(new WindowAdapter()

  {

   public void windowClosing(WindowEvent 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("服务器开始于:"+serverSocket.getInetAddress().getLocalHost()+":"+serverSocket.getLocalPort()+"\n");

 

   while(true)

   {

    clientSocket=serverSocket.accept();

         server.messageBoard.append("用户连接:"+clientSocket+"\n");

 

    DataOutputStream outData=new DataOutputStream(clientSocket.getOutputStream());

 

    clientDataHash.put(clientSocket,outData);

    clientNameHash.put(clientSocket,("新来客"+clientAccessNumber++));

 

    ServerThread thread=new ServerThread(clientSocket,clientDataHash,clientNameHash,chessPeerHash,server);

 

    thread.start();

   }

  }

  catch(IOException ex)

  {

   System.out.println("已经有服务器在运行. \n");

  }

 

 

}

 

 public void actionPerformed(ActionEvent e)

 {

  if(e.getSource()==messageClearButton)

  {

   server.messageBoard.setText("");

  }

  if(e.getSource()==serverStatusButton)

  {

   try

   {

    server.messageBoard.append("服务器信息:"+serverSocket.getInetAddress().getLocalHost()+":"+serverSocket.getLocalPort()+"\n");

      }

      catch(Exception ee)

      {

    System.out.println("serverSocket.getInetAddress().getLocalHost() error \n");

   }

  }

  if(e.getSource()==serverOffButton)

  {

   System.exit(0);

  }

 }

 

 public static void main(String args[])

 {

  chessServer chessServer=new chessServer();

 }

}

总结与体会:

在这次试验中遇到的问题有:

1.在进行git实验的时候,空格容易漏掉,出现错误,反复对照老师的截图后找到问题所在,修改成功;

2.在进行HelloWorld编写时对VIM应用不是很清楚,编完代码后不知道怎么保存退出,在群里询问同学后,成功的运用,esc后输入:wp的方法解决,完成实验内容,达到老师的截图效果;

3.整个实验来看,对于git命令操作不熟悉,有关命令不知道该怎么运用。在结对实验中通过对五子棋的代码的编辑,对java语言有了进一步的了解和认识。体会到java语言的广泛应用性。

PSP时间:

步骤

耗时

百分比

需求分析

30min

10

设计

60min

20

代码实现

150min

50

测试

45min

15

分析总结

15min

5

                          

 结对伙伴:20135316 王剑桥 

              博客地址:http://www.cnblogs.com/20135316wjq/ 

实验楼第三次试验报告

标签:

原文地址:http://www.cnblogs.com/lxq20135309/p/4553559.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!