服务器端部分代码如下
- Java code
//其中socketA和socketB是五子棋对战的双方 class BeginGame implements Runnable{ private Socket socketA = null; private Socket socketB = null; private boolean isBlack = true; public BeginGame(Socket socketA,Socket socketB){ this.socketA = socketA; this.socketB = socketB; } public void run(){ int x;//x,y用来记录棋盘上棋子的坐标 int y; boolean first = true; while(true){ try { //获取对战双方的输出流 DataOutputStream outA = new DataOutputStream(socketA.getOutputStream()); DataOutputStream outB = new DataOutputStream(socketB.getOutputStream()); if(first){ //在游戏刚开始的时候,分别发送信息给对战的双发,1表示为黑棋,2表示为白棋 outA.writeInt(1); outB.writeInt(2); first = false; } DataInputStream inA = new DataInputStream(socketA.getInputStream()); DataInputStream inB = new DataInputStream(socketB.getInputStream()); //isBlack用于判定是黑棋发送来的信息还是白棋,初始化为false if(isBlack){ //读取黑方发送来的x,y坐标值 x = inA.readInt(); y = inA.readInt(); System.out.println("black: "+x+" "+y); //gamePoint用来存储整个棋盘的信息,初始全为0,为黑棋时设为1,白棋时设为2 //如果该点上已有棋子,则重新等待黑方再次发送坐标 if(gamePoint[x][y]!=0) continue; else gamePoint[x][y] = 1; //将黑方发送来的x,y坐标值发送给白方 outB.writeInt(x); outB.writeInt(y); isBlack = false; }else{ //处理白方发送来的信息 x = inB.readInt(); y = inB.readInt(); if(gamePoint[x][y]!=0) continue; else gamePoint[x][y] = 2; System.out.println("white "+x+" "+y); outA.writeInt(x); outA.writeInt(y); isBlack = true; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
客户端代码如下
- Java code
gamePanel.addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent e){ if(beginGame){ //读取鼠标点击的坐标值,转化为对应的数组的x,y值 int x = (e.getX()-gamePanel.cellSize_x/2)/gamePanel.cellSize_x; int y = (e.getY()-gamePanel.cellSize_y/2)/gamePanel.cellSize_y; try { //向服务器端发送坐标值 out.writeInt(x); out.writeInt(y); } catch (IOException e1) { e1.printStackTrace(); } gamePanel.repaint(); } } });
运行两个对战的客户端,然后在棋盘上点击一次之后,服务器端会有时会将处理黑棋和白棋的的代码全部执行一遍,即if和else的都执行了,有时候又可以让黑方连续点击或者白方连续点击,,不知道是哪出了问题?是不是writeInt和readInt方法用错了
------解决方案--------------------
- Java code
private boolean isBlack = true; //isBlack用于判定是黑棋发送来的信息还是白棋,初始化为false