服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - JAVA教程 - Java实现五子棋网络版

Java实现五子棋网络版

2021-04-16 11:37OnePointC JAVA教程

这篇文章主要为大家详细介绍了基于Java编写的网络五子棋,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了java实现五子棋网络版的具体代码,供大家参考,具体内容如下

需求分析:

对于网络五子棋而言,在普通五子棋的基础上需要添加以下功能:

1.拥有服务器端和客户端,用户通过客户端登录服务器后可与其他登录的用户进行对弈

2.服务器支持多组用户同时进行对弈

3.用户可以在服务器上创建新游戏或加入已创建的游戏

4.用户在下棋的时候可以进行聊天交流

由上可以知道需要实现的功能:

·提供服务器和客户端的功能

·服务器将监听客户端的登录情况并允许多个客户端进行登录

·用户通过客户端可以登录服务器,之后可以看到服务器当前在线的其他用户,并与他们进行聊天等

·用户登录服务器后,可以创建新的五子棋游戏或加入已创建的五子棋游戏

·用户通过客户端可以像普通五子棋那样与其他用户对弈

根据功能将网络五子棋分为4个模块:即用户面板模块、棋盘面板模块、五子棋服务器模块、五子棋客户端模块

Java实现五子棋网络版

下面我们开始进行编译用户面板模块:

1.开发用户列表面板

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.awt.*;
 
/**
 * created by administrator on 2016/11/21.
 */
//初始状态下将添加10个名称为“无用户“的信息到列表中,说明服务器最多支持10个用户同时在线
//该列表被添加到面板中,使用“borderlayout”布局格式
public class userlistpad extends panel{
  public list userlist=new list(10);
 
  public userlistpad(){
    setlayout(new borderlayout());
    for(int i=0;i<10;i++){
      userlist.add(i+"."+"无用户");
    }
    add(userlist,borderlayout.center);
  }
}

2.开发用户聊天面板

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import javax.swing.*;
import java.awt.*;
 
/**
 * created by administrator on 2016/11/21.
 */
//聊天面板为一个textarea视图控件,拥有一个垂直方向的滚动条。
//该textarea被添加到面板中,使用“borderlayout”布局格式。
public class userchatpad extends jpanel{
  public jtextarea chattextarea=new jtextarea("命令区域",18,20);
  public userchatpad(){
    setlayout(new borderlayout());
    chattextarea.setautoscrolls(true);
    chattextarea.setlinewrap(true);
    add(chattextarea,borderlayout.center);
  }
}

3.开发用户输入面板

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import javax.swing.*;
import java.awt.*;
 
/**
 * created by administrator on 2016/11/21.
 */
//面板包含两个视图控件
//contentinpitted为textfield控件,用户可以在其中输入聊天信息
public class userinputpad extends jpanel{
  public jtextfield contentinputted = new jtextfield("",26);
  public jcombobox userchoice = new jcombobox();
 
  public userinputpad(){
    setlayout(new flowlayout(flowlayout.left));
    for(int i=0;i<50;i++){
      userchoice.additem(i+"."+"无用户");
    }
    userchoice.setsize(60,24);
    add(userchoice);
    add(contentinputted);
  }
}

4.开发用户操作面板

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import javax.swing.*;
import java.awt.*;
 
/**
 * created by administrator on 2016/11/21.
 */
public class usercontrolpad extends jpanel {
  public jlabel iplabel = new jlabel("ip",jlabel.left);
  public jtextfield ipinputted = new jtextfield("localhost",10);
  public jbutton connectbutton = new jbutton("连接到服务器");
  public jbutton createbutton = new jbutton("创建游戏");
  public jbutton joinbutton = new jbutton("加入游戏");
  public jbutton cancelbutton = new jbutton("放弃游戏");
  public jbutton exitbutton = new jbutton("退出游戏");
  public usercontrolpad(){
    setlayout(new flowlayout(flowlayout.left));
    setbackground(color.light_gray);
    add(iplabel);
    add(ipinputted);
    add(connectbutton);
    add(createbutton);
    add(joinbutton);
    add(cancelbutton);
    add(exitbutton);
  }
}

下面开始开发棋盘面板模块

1.开发黑棋类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.awt.*;
 
/**
 * created by administrator on 2016/11/21.
 */
public class firpointblack extends canvas {
  firpad padbelonged; // 黑棋所属的棋盘
 
  public firpointblack(firpad padbelonged)
  {
    setsize(20, 20); // 设置棋子大小
    this.padbelonged = padbelonged;
  }
 
  public void paint(graphics g)
  { // 画棋子
    g.setcolor(color.black);
    g.filloval(0, 0, 14, 14);
  }
}

2.开发白棋类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.awt.*;
 
/**
 * created by administrator on 2016/11/21.
 */
public class firpointwhite extends canvas{
  firpad padbelonged; // 白棋所属的棋盘
 
  public firpointwhite(firpad padbelonged)
  {
    setsize(20, 20);
    this.padbelonged = padbelonged;
  }
 
  public void paint(graphics g)
  { // 画棋子
    g.setcolor(color.white);
    g.filloval(0, 0, 14, 14);
  }
}

3.开发棋盘面板

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
 
import javax.swing.jtextfield;
 
 
/**
 * created by administrator on 2016/11/21.
 */
public class firpad extends panel implements mouselistener,actionlistener{
  // 鼠标是否能使用
  public boolean ismouseenabled = false;
  // 是否胜利
  public boolean iswinned = false;
  // 是否在下棋中
  public boolean isgaming = false;
  // 棋子的x轴坐标位
  public int chessx_pos = -1;
  // 棋子的y轴坐标位
  public int chessy_pos = -1;
  // 棋子的颜色
  public int chesscolor = 1;
  // 黑棋x轴坐标位数组
  public int chessblack_xpos[] = new int[200];
  // 黑棋y轴坐标位数组
  public int chessblack_ypos[] = new int[200];
  // 白棋x轴坐标位数组
  public int chesswhite_xpos[] = new int[200];
  // 白棋y轴坐标位数组
  public int chesswhite_ypos[] = new int[200];
  // 黑棋数量
  public int chessblackcount = 0;
  // 白棋数量
  public int chesswhitecount = 0;
  // 黑棋获胜次数
  public int chessblackvictimes = 0;
  // 白棋获胜次数
  public int chesswhitevictimes = 0;
  // 套接口
  public socket chesssocket;
  public datainputstream inputdata;
  public dataoutputstream outputdata;
  public string chessselfname = null;
  public string chesspeername = null;
  public string host = null;
  public int port = 4331;
  public textfield statustext = new textfield("请连接服务器!");
  public firthread firthread = new firthread(this);
 
  public firpad()
  {
    setsize(440, 440);
    setlayout(null);
    setbackground(color.light_gray);
    addmouselistener(this);
    add(statustext);
    statustext.setbounds(new rectangle(40, 5, 360, 24));
    statustext.seteditable(false);
  }
 
  // 连接到主机
  public boolean connectserver(string serverip, int serverport) throws exception
  {
    try
    {
      // 取得主机端口
      chesssocket = new socket(serverip, serverport);
      // 取得输入流
      inputdata = new datainputstream(chesssocket.getinputstream());
      // 取得输出流
      outputdata = new dataoutputstream(chesssocket.getoutputstream());
      firthread.start();
      return true;
    }
    catch (ioexception ex)
    {
      statustext.settext("连接失败! \n");
    }
    return false;
  }
 
  // 设定胜利时的棋盘状态
  public void setvicstatus(int vicchesscolor)
  {
    // 清空棋盘
    this.removeall();
    // 将黑棋的位置设置到零点
    for (int i = 0; i <= chessblackcount; i++)
    {
      chessblack_xpos[i] = 0;
      chessblack_ypos[i] = 0;
    }
    // 将白棋的位置设置到零点
    for (int i = 0; i <= chesswhitecount; i++)
    {
      chesswhite_xpos[i] = 0;
      chesswhite_ypos[i] = 0;
    }
    // 清空棋盘上的黑棋数
    chessblackcount = 0;
    // 清空棋盘上的白棋数
    chesswhitecount = 0;
    add(statustext);
    statustext.setbounds(40, 5, 360, 24);
    if (vicchesscolor == 1)
    { // 黑棋胜
      chessblackvictimes++;
      statustext.settext("黑方胜,黑:白 " + chessblackvictimes + ":" + chesswhitevictimes
          + ",游戏重启,等待白方...");
    }
    else if (vicchesscolor == -1)
    { // 白棋胜
      chesswhitevictimes++;
      statustext.settext("白方胜,黑:白 " + chessblackvictimes + ":" + chesswhitevictimes
          + ",游戏重启,等待黑方...");
    }
  }
 
  // 取得指定棋子的位置
  public void setlocation(int xpos, int ypos, int chesscolor)
  {
    if (chesscolor == 1)
    { // 棋子为黑棋时
      chessblack_xpos[chessblackcount] = xpos * 20;
      chessblack_ypos[chessblackcount] = ypos * 20;
      chessblackcount++;
    }
    else if (chesscolor == -1)
    { // 棋子为白棋时
      chesswhite_xpos[chesswhitecount] = xpos * 20;
      chesswhite_ypos[chesswhitecount] = ypos * 20;
      chesswhitecount++;
    }
  }
 
  // 判断当前状态是否为胜利状态
  public boolean checkvicstatus(int xpos, int ypos, int chesscolor)
  {
    int chesslinkedcount = 1; // 连接棋子数
    int chesslinkedcompare = 1; // 用于比较是否要继续遍历一个棋子的相邻网格
    int chesstocompareindex = 0; // 要比较的棋子在数组中的索引位置
    int closegrid = 1; // 相邻网格的位置
    if (chesscolor == 1)
    { // 黑棋时
      chesslinkedcount = 1; // 将该棋子自身算入的话,初始连接数为1
      //以下每对for循环语句为一组,因为下期的位置能位于中间而非两端
      for (closegrid = 1; closegrid <= 4; closegrid++)
      { // 遍历相邻4个网格
        for (chesstocompareindex = 0; chesstocompareindex <= chessblackcount; chesstocompareindex++)
        { // 遍历棋盘上所有黑棋子
          if (((xpos + closegrid) * 20 == chessblack_xpos[chesstocompareindex])
              && ((ypos * 20) == chessblack_ypos[chesstocompareindex]))
          { // 判断当前下的棋子的右边4个棋子是否都为黑棋
            chesslinkedcount = chesslinkedcount + 1; // 连接数加1
            if (chesslinkedcount == 5)
            { // 五子相连时,胜利
              return true;
            }
          }
        }
        if (chesslinkedcount == (chesslinkedcompare + 1)) {
          chesslinkedcompare++;
        }
        else {// 若中间有一个棋子非黑棋,则会进入此分支,此时无需再遍历
          break;
        }
      }
      for (closegrid = 1; closegrid <= 4; closegrid++)
      {
        for (chesstocompareindex = 0; chesstocompareindex <= chessblackcount; chesstocompareindex++)
        {
          if (((xpos - closegrid) * 20 == chessblack_xpos[chesstocompareindex])
              && (ypos * 20 == chessblack_ypos[chesstocompareindex]))
          { // 判断当前下的棋子的左边4个棋子是否都为黑棋
            chesslinkedcount++;
            if (chesslinkedcount == 5)
            {
              return true;
            }
          }
        }
        if (chesslinkedcount == (chesslinkedcompare + 1)) {
          chesslinkedcompare++;
        }
        else {
          break;
        }
      }
      // 进入新的一组for循环时要将连接数等重置
      chesslinkedcount = 1;
      chesslinkedcompare = 1;
      for (closegrid = 1; closegrid <= 4; closegrid++)
      {
        for (chesstocompareindex = 0; chesstocompareindex <= chessblackcount; chesstocompareindex++)
        {
          if ((xpos * 20 == chessblack_xpos[chesstocompareindex])
              && ((ypos + closegrid) * 20 == chessblack_ypos[chesstocompareindex]))
          { // 判断当前下的棋子的上边4个棋子是否都为黑棋
            chesslinkedcount++;
            if (chesslinkedcount == 5)
            {
              return true;
            }
          }
        }
        if (chesslinkedcount == (chesslinkedcompare + 1)) {
          chesslinkedcompare++;
        }
        else {
          break;
        }
      }
      for (closegrid = 1; closegrid <= 4; closegrid++)
      {
        for (chesstocompareindex = 0; chesstocompareindex <= chessblackcount; chesstocompareindex++)
        {
          if ((xpos * 20 == chessblack_xpos[chesstocompareindex])
              && ((ypos - closegrid) * 20 == chessblack_ypos[chesstocompareindex]))
          { // 判断当前下的棋子的下边4个棋子是否都为黑棋
            chesslinkedcount++;
            if (chesslinkedcount == 5)
            {
              return true;
            }
          }
        }
        if (chesslinkedcount == (chesslinkedcompare + 1)) {
          chesslinkedcompare++;
        }
        else {
          break;
        }
      }
      chesslinkedcount = 1;
      chesslinkedcompare = 1;
      for (closegrid = 1; closegrid <= 4; closegrid++)
      {
        for (chesstocompareindex = 0; chesstocompareindex <= chessblackcount; chesstocompareindex++)
        {
          if (((xpos - closegrid) * 20 == chessblack_xpos[chesstocompareindex])
              && ((ypos + closegrid) * 20 == chessblack_ypos[chesstocompareindex]))
          { // 判断当前下的棋子的左上方向4个棋子是否都为黑棋
            chesslinkedcount++;
            if (chesslinkedcount == 5)
            {
              return true;
            }
          }
        }
        if (chesslinkedcount == (chesslinkedcompare + 1)) {
          chesslinkedcompare++;
        }
        else {
          break;
        }
      }
      for (closegrid = 1; closegrid <= 4; closegrid++)
      {
        for (chesstocompareindex = 0; chesstocompareindex <= chessblackcount; chesstocompareindex++)
        {
          if (((xpos + closegrid) * 20 == chessblack_xpos[chesstocompareindex])
              && ((ypos - closegrid) * 20 == chessblack_ypos[chesstocompareindex]))
          { // 判断当前下的棋子的右下方向4个棋子是否都为黑棋
            chesslinkedcount++;
            if (chesslinkedcount == 5)
            {
              return true;
            }
          }
        }
        if (chesslinkedcount == (chesslinkedcompare + 1)) {
          chesslinkedcompare++;
        }
        else {
          break;
        }
      }
      chesslinkedcount = 1;
      chesslinkedcompare = 1;
      for (closegrid = 1; closegrid <= 4; closegrid++)
      {
        for (chesstocompareindex = 0; chesstocompareindex <= chessblackcount; chesstocompareindex++)
        {
          if (((xpos + closegrid) * 20 == chessblack_xpos[chesstocompareindex])
              && ((ypos + closegrid) * 20 == chessblack_ypos[chesstocompareindex]))
          { // 判断当前下的棋子的右上方向4个棋子是否都为黑棋
            chesslinkedcount++;
            if (chesslinkedcount == 5)
            {
              return true;
            }
          }
        }
        if (chesslinkedcount == (chesslinkedcompare + 1)) {
          chesslinkedcompare++;
        }
        else {
          break;
        }
      }
      for (closegrid = 1; closegrid <= 4; closegrid++)
      {
        for (chesstocompareindex = 0; chesstocompareindex <= chessblackcount; chesstocompareindex++)
        {
          if (((xpos - closegrid) * 20 == chessblack_xpos[chesstocompareindex])
              && ((ypos - closegrid) * 20 == chessblack_ypos[chesstocompareindex]))
          { // 判断当前下的棋子的左下方向4个棋子是否都为黑棋
            chesslinkedcount++;
            if (chesslinkedcount == 5)
            {
              return true;
            }
          }
        }
        if (chesslinkedcount == (chesslinkedcompare + 1)) {
          chesslinkedcompare++;
        }
        else {
          break;
        }
      }
    }
    else if (chesscolor == -1)
    { // 白棋时
      chesslinkedcount = 1;
      for (closegrid = 1; closegrid <= 4; closegrid++)
      {
        for (chesstocompareindex = 0; chesstocompareindex <= chesswhitecount; chesstocompareindex++)
        {
          if (((xpos + closegrid) * 20 == chesswhite_xpos[chesstocompareindex])
              && (ypos * 20 == chesswhite_ypos[chesstocompareindex]))
          {// 判断当前下的棋子的右边4个棋子是否都为白棋
            chesslinkedcount++;
            if (chesslinkedcount == 5)
            {
              return true;
            }
          }
        }
        if (chesslinkedcount == (chesslinkedcompare + 1)) {
          chesslinkedcompare++;
        }
        else {
          break;
        }
      }
      for (closegrid = 1; closegrid <= 4; closegrid++)
      {
        for (chesstocompareindex = 0; chesstocompareindex <= chesswhitecount; chesstocompareindex++)
        {
          if (((xpos - closegrid) * 20 == chesswhite_xpos[chesstocompareindex])
              && (ypos * 20 == chesswhite_ypos[chesstocompareindex]))
          {// 判断当前下的棋子的左边4个棋子是否都为白棋
            chesslinkedcount++;
            if (chesslinkedcount == 5)
            {
              return true;
            }
          }
        }
        if (chesslinkedcount == (chesslinkedcompare + 1)) {
          chesslinkedcompare++;
        }
        else {
          break;
        }
      }
      chesslinkedcount = 1;
      chesslinkedcompare = 1;
      for (closegrid = 1; closegrid <= 4; closegrid++)
      {
        for (chesstocompareindex = 0; chesstocompareindex <= chesswhitecount; chesstocompareindex++)
        {
          if ((xpos * 20 == chesswhite_xpos[chesstocompareindex])
              && ((ypos + closegrid) * 20 == chesswhite_ypos[chesstocompareindex]))
          {// 判断当前下的棋子的上边4个棋子是否都为白棋
            chesslinkedcount++;
            if (chesslinkedcount == 5)
            {
              return true;
            }
          }
        }
        if (chesslinkedcount == (chesslinkedcompare + 1)) {
          chesslinkedcompare++;
        }
        else {
          break;
        }
      }
      for (closegrid = 1; closegrid <= 4; closegrid++)
      {
        for (chesstocompareindex = 0; chesstocompareindex <= chesswhitecount; chesstocompareindex++)
        {
          if ((xpos * 20 == chesswhite_xpos[chesstocompareindex])
              && ((ypos - closegrid) * 20 == chesswhite_ypos[chesstocompareindex]))
          {// 判断当前下的棋子的下边4个棋子是否都为白棋
            chesslinkedcount++;
            if (chesslinkedcount == 5)
            {
              return true;
            }
          }
        }
        if (chesslinkedcount == (chesslinkedcompare + 1)) {
          chesslinkedcompare++;
        }
        else {
          break;
        }
      }
      chesslinkedcount = 1;
      chesslinkedcompare = 1;
      for (closegrid = 1; closegrid <= 4; closegrid++)
      {
        for (chesstocompareindex = 0; chesstocompareindex <= chesswhitecount; chesstocompareindex++)
        {
          if (((xpos - closegrid) * 20 == chesswhite_xpos[chesstocompareindex])
              && ((ypos + closegrid) * 20 == chesswhite_ypos[chesstocompareindex]))
          {// 判断当前下的棋子的左上方向4个棋子是否都为白棋
            chesslinkedcount++;
            if (chesslinkedcount == 5)
            {
              return true;
            }
          }
        }
        if (chesslinkedcount == (chesslinkedcompare + 1)) {
          chesslinkedcompare++;
        }
        else {
          break;
        }
      }
      for (closegrid = 1; closegrid <= 4; closegrid++)
      {
        for (chesstocompareindex = 0; chesstocompareindex <= chesswhitecount; chesstocompareindex++)
        {
          if (((xpos + closegrid) * 20 == chesswhite_xpos[chesstocompareindex])
              && ((ypos - closegrid) * 20 == chesswhite_ypos[chesstocompareindex]))
          {// 判断当前下的棋子的右下方向4个棋子是否都为白棋
            chesslinkedcount++;
            if (chesslinkedcount == 5)
            {
              return true;
            }
          }
        }
        if (chesslinkedcount == (chesslinkedcompare + 1)) {
          chesslinkedcompare++;
        }
        else {
          break;
        }
      }
      chesslinkedcount = 1;
      chesslinkedcompare = 1;
      for (closegrid = 1; closegrid <= 4; closegrid++)
      {
        for (chesstocompareindex = 0; chesstocompareindex <= chesswhitecount; chesstocompareindex++)
        {
          if (((xpos + closegrid) * 20 == chesswhite_xpos[chesstocompareindex])
              && ((ypos + closegrid) * 20 == chesswhite_ypos[chesstocompareindex]))
          {// 判断当前下的棋子的右上方向4个棋子是否都为白棋
            chesslinkedcount++;
            if (chesslinkedcount == 5)
            {
              return true;
            }
          }
        }
        if (chesslinkedcount == (chesslinkedcompare + 1)) {
          chesslinkedcompare++;
        }
        else {
          break;
        }
      }
      for (closegrid = 1; closegrid <= 4; closegrid++)
      {
        for (chesstocompareindex = 0; chesstocompareindex <= chesswhitecount; chesstocompareindex++)
        {
          if (((xpos - closegrid) * 20 == chesswhite_xpos[chesstocompareindex])
              && ((ypos - closegrid) * 20 == chesswhite_ypos[chesstocompareindex]))
          {// 判断当前下的棋子的左下方向4个棋子是否都为白棋
            chesslinkedcount++;
            if (chesslinkedcount == 5)
            {
              return (true);
            }
          }
        }
        if (chesslinkedcount == (chesslinkedcompare + 1)) {
          chesslinkedcompare++;
        }
        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 paintfirpoint(int xpos, int ypos, int chesscolor)
  {
    firpointblack firpblack = new firpointblack(this);
    firpointwhite firpwhite = new firpointwhite(this);
    if (chesscolor == 1 && ismouseenabled)
    { // 黑棋
      // 设置棋子的位置
      setlocation(xpos, ypos, chesscolor);
      // 取得当前局面状态
      iswinned = checkvicstatus(xpos, ypos, chesscolor);
      if (iswinned == false)
      { // 非胜利状态
        firthread.sendmessage("/" + chesspeername + " /chess "
            + xpos + " " + ypos + " " + chesscolor);
        this.add(firpblack); // 将棋子添加到棋盘中
        firpblack.setbounds(xpos * 20 - 7,
            ypos * 20 - 7, 16, 16); // 设置棋子边界
        statustext.settext("黑(第" + chessblackcount + "步)"
            + xpos + " " + ypos + ",轮到白方.");
        ismouseenabled = false; // 将鼠标设为不可用
      }
      else
      { // 胜利状态
        firthread.sendmessage("/" + chesspeername + " /chess "
            + xpos + " " + ypos + " " + chesscolor);
        this.add(firpblack);
        firpblack.setbounds(xpos * 20 - 7,
            ypos * 20 - 7, 16, 16);
        setvicstatus(1); // 调用胜利方法,传入参数为黑棋胜利
        ismouseenabled = false;
      }
    }
    else if (chesscolor == -1 && ismouseenabled)
    { // 白棋
      setlocation(xpos, ypos, chesscolor);
      iswinned = checkvicstatus(xpos, ypos, chesscolor);
      if (iswinned == false)
      {
        firthread.sendmessage("/" + chesspeername + " /chess "
            + xpos + " " + ypos + " " + chesscolor);
        this.add(firpwhite);
        firpwhite.setbounds(xpos * 20 - 7,
            ypos * 20 - 7, 16, 16);
        statustext.settext("白(第" + chesswhitecount + "步)"
            + xpos + " " + ypos + ",轮到黑方.");
        ismouseenabled = false;
      }
      else
      {
        firthread.sendmessage("/" + chesspeername + " /chess "
            + xpos + " " + ypos + " " + chesscolor);
        this.add(firpwhite);
        firpwhite.setbounds(xpos * 20 - 7,
            ypos * 20 - 7, 16, 16);
        setvicstatus(-1); // 调用胜利方法,传入参数为白棋
        ismouseenabled = false;
      }
    }
  }
 
  // 画网络棋盘
  public void paintnetfirpoint(int xpos, int ypos, int chesscolor)
  {
    firpointblack firpblack = new firpointblack(this);
    firpointwhite firpwhite = new firpointwhite(this);
    setlocation(xpos, ypos, chesscolor);
    if (chesscolor == 1)
    {
      iswinned = checkvicstatus(xpos, ypos, chesscolor);
      if (iswinned == false)
      {
        this.add(firpblack);
        firpblack.setbounds(xpos * 20 - 7,
            ypos * 20 - 7, 16, 16);
        statustext.settext("黑(第" + chessblackcount + "步)"
            + xpos + " " + ypos + ",轮到白方.");
        ismouseenabled = true;
      }
      else
      {
        firthread.sendmessage("/" + chesspeername + " /victory "
            + chesscolor);//djr
        this.add(firpblack);
        firpblack.setbounds(xpos * 20 - 7,
            ypos * 20 - 7, 16, 16);
        setvicstatus(1);
        ismouseenabled = true;
      }
    }
    else if (chesscolor == -1)
    {
      iswinned = checkvicstatus(xpos, ypos, chesscolor);
      if (iswinned == false)
      {
        this.add(firpwhite);
        firpwhite.setbounds(xpos * 20 - 7,
            ypos * 20 - 7, 16, 16);
        statustext.settext("白(第" + chesswhitecount + "步)"
            + xpos + " " + ypos + ",轮到黑方.");
        ismouseenabled = true;
      }
      else
      {
        firthread.sendmessage("/" + chesspeername + " /victory "
            + chesscolor);
        this.add(firpwhite);
        firpwhite.setbounds(xpos * 20 - 7,
            ypos * 20 - 7, 16, 16);
        setvicstatus(-1);
        ismouseenabled = true;
      }
    }
  }
 
  // 捕获下棋事件
  public void mousepressed(mouseevent e)
  {
    if (e.getmodifiers() == inputevent.button1_mask)
    {
      chessx_pos = (int) e.getx();
      chessy_pos = (int) e.gety();
      int a = (chessx_pos + 10) / 20, b = (chessy_pos + 10) / 20;
      if (chessx_pos / 20 < 2 || chessy_pos / 20 < 2
          || chessx_pos / 20 > 19 || chessy_pos / 20 > 19)
      {
        // 下棋位置不正确时,不执行任何操作
      }
      else
      {
        paintfirpoint(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){}
}

4.开发棋盘线程

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.util.stringtokenizer;
import java.io.ioexception;
 
/**
 * created by administrator on 2016/11/21.
 */
public class firthread extends thread{
  firpad currpad; // 当前线程的棋盘
 
  public firthread(firpad currpad)
  {
    this.currpad = currpad;
  }
 
  // 处理取得的信息
  public void dealwithmsg(string msgreceived)
  {
    if (msgreceived.startswith("/chess "))
    { // 收到的信息为下棋
      stringtokenizer usermsgtoken = new stringtokenizer(msgreceived, " ");
      // 表示棋子信息的数组、0索引为:x坐标;1索引位:y坐标;2索引位:棋子颜色
      string[] chessinfo = { "-1", "-1", "0" };
      int i = 0; // 标志位
      string chessinfotoken;
      while (usermsgtoken.hasmoretokens())
      {
        chessinfotoken = (string) usermsgtoken.nexttoken(" ");
        if (i >= 1 && i <= 3)
        {
          chessinfo[i - 1] = chessinfotoken;
        }
        i++;
      }
      currpad.paintnetfirpoint(integer.parseint(chessinfo[0]), integer
          .parseint(chessinfo[1]), integer.parseint(chessinfo[2]));
    }
    else if (msgreceived.startswith("/yourname "))
    { // 收到的信息为改名
      currpad.chessselfname = msgreceived.substring(10);
    }
    else if (msgreceived.equals("/error"))
    { // 收到的为错误信息
      currpad.statustext.settext("用户不存在,请重新加入!");
    }
  }
 
  // 发送信息
  public void sendmessage(string sndmessage)
  {
    try
    {
      currpad.outputdata.writeutf(sndmessage);
    }
    catch (exception ea)
    {
      ea.printstacktrace();;
    }
  }
 
  public void run()
  {
    string msgreceived = "";
    try
    {
      while (true)
      { // 等待信息输入
        msgreceived = currpad.inputdata.readutf();
        dealwithmsg(msgreceived);
      }
    }
    catch (ioexception es){}
  }
}

下面开始开发服务器模块

1.开发服务器信息面板

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.awt.borderlayout;
import java.awt.color;
import java.awt.flowlayout;
import java.awt.label;
import java.awt.panel;
import java.awt.textarea;
 
import javax.swing.jlabel;
 
/**
 * created by administrator on 2016/11/21.
 */
public class servermsgpanel extends panel {
  public textarea msgtextarea = new textarea("", 22, 50,
      textarea.scrollbars_vertical_only);
  public jlabel statuslabel = new jlabel("当前连接数:", label.left);
  public panel msgpanel = new panel();
  public panel statuspanel = new panel();
  public servermsgpanel()
  {
    setsize(350, 300);
    setbackground(color.light_gray);
    setlayout(new borderlayout());
    msgpanel.setlayout(new flowlayout());
    msgpanel.setsize(210, 210);
    statuspanel.setlayout(new borderlayout());
    statuspanel.setsize(210, 50);
    msgpanel.add(msgtextarea);
    statuspanel.add(statuslabel, borderlayout.west);
    add(msgpanel, borderlayout.center);
    add(statuspanel, borderlayout.north);
  }
 
}

2.开发服务器进程

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import java.io.datainputstream;
import java.io.dataoutputstream;
import java.io.ioexception;
import java.net.socket;
import java.util.enumeration;
import java.util.hashtable;
import java.util.stringtokenizer;
 
/**
 * created by administrator on 2016/11/21.
 */
public class firserverthread extends thread{
  socket clientsocket; // 保存客户端套接口信息
  hashtable clientdatahash; // 保存客户端端口与输出流对应的hash
  hashtable clientnamehash; // 保存客户端套接口和客户名对应的hash
  hashtable chesspeerhash; // 保存游戏创建者和游戏加入者对应的hash
  servermsgpanel servermsgpanel;
  boolean isclientclosed = false;
 
  public firserverthread(socket clientsocket, hashtable clientdatahash,
              hashtable clientnamehash, hashtable chesspeerhash,
              servermsgpanel server)
  {
    this.clientsocket = clientsocket;
    this.clientdatahash = clientdatahash;
    this.clientnamehash = clientnamehash;
    this.chesspeerhash = chesspeerhash;
    this.servermsgpanel = server;
  }
 
  public void dealwithmsg(string msgreceived)
  {
    string clientname;
    string peername;
    if (msgreceived.startswith("/"))
    {
      if (msgreceived.equals("/list"))
      { // 收到的信息为更新用户列表
        feedback(getuserlist());
      }
      else if (msgreceived.startswith("/creatgame [inchess]"))
      { // 收到的信息为创建游戏
        string gamecreatername = 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());
      }
      else if (msgreceived.startswith("/joingame "))
      { // 收到的信息为加入游戏时
        stringtokenizer usertokens = new stringtokenizer(msgreceived, " ");
        string usertoken;
        string gamecreatorname;
        string gamepaticipantname;
        string[] playernames = { "0", "0" };
        int nameindex = 0;
        while (usertokens.hasmoretokens())
        {
          usertoken = (string) usertokens.nexttoken(" ");
          if (nameindex >= 1 && nameindex <= 2)
          {
            playernames[nameindex - 1] = usertoken; // 取得游戏者命
          }
          nameindex++;
        }
        gamecreatorname = playernames[0];
        gamepaticipantname = playernames[1];
        if (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 (exception ez)
          {
            ez.printstacktrace();
          }
        }
      }
      else if (msgreceived.startswith("/[inchess]"))
      { // 收到的信息为游戏中时
        int firstlocation = 0, lastlocation;
        lastlocation = msgreceived.indexof(" ", 0);
        peername = msgreceived.substring((firstlocation + 1), lastlocation);
        msgreceived = msgreceived.substring((lastlocation + 1));
        if (sendgamepeermsg(peername, msgreceived))
        {
          feedback("/error");
        }
      }
      else if (msgreceived.startswith("/giveup "))
      { // 收到的信息为放弃游戏时
        string chessclientname = 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));
          }
        }
      }
      else
      { // 收到的信息为其它信息时
        int lastlocation = msgreceived.indexof(" ", 0);
        if (lastlocation == -1)
        {
          feedback("无效命令");
          return;
        }
      }
    }
    else
    {
      msgreceived = clientnamehash.get(clientsocket) + ">" + msgreceived;
      servermsgpanel.msgtextarea.append(msgreceived + "\n");
      sendpublicmsg(msgreceived);
      servermsgpanel.msgtextarea.setcaretposition(servermsgpanel.msgtextarea.gettext()
          .length());
    }
  }
 
  // 发送公开信息
  public void sendpublicmsg(string publicmsg)
  {
    synchronized (clientdatahash)
    {
      for (enumeration enu = clientdatahash.elements(); enu
          .hasmoreelements();)
      {
        dataoutputstream outputdata = (dataoutputstream) enu.nextelement();
        try
        {
          outputdata.writeutf(publicmsg);
        }
        catch (ioexception es)
        {
          es.printstacktrace();
        }
      }
    }
  }
 
  // 发送信息给指定的游戏中的用户
  public boolean sendgamepeermsg(string gamepeertarget, string gamepeermsg)
  {
    for (enumeration enu = clientdatahash.keys(); enu.hasmoreelements();)
    { // 遍历以取得游戏中的用户的套接口
      socket userclient = (socket) enu.nextelement();
      if (gamepeertarget.equals((string) clientnamehash.get(userclient))
          && !gamepeertarget.equals((string) clientnamehash
          .get(clientsocket)))
      { // 找到要发送信息的用户时
        synchronized (clientdatahash)
        {
          // 建立输出流
          dataoutputstream peeroutdata = (dataoutputstream) clientdatahash
              .get(userclient);
          try
          {
            // 发送信息
            peeroutdata.writeutf(gamepeermsg);
          }
          catch (ioexception es)
          {
            es.printstacktrace();
          }
        }
        return false;
      }
    }
    return true;
  }
 
  // 发送反馈信息给连接到主机的人
  public void feedback(string feedbackmsg)
  {
    synchronized (clientdatahash)
    {
      dataoutputstream outputdata = (dataoutputstream) clientdatahash
          .get(clientsocket);
      try
      {
        outputdata.writeutf(feedbackmsg);
      }
      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;
  }
 
  // 根据value值从hashtable中取得相应的key
  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 sendinitmsg()
  {
    sendpublicmsg(getuserlist());
    feedback("/yourname " + (string) clientnamehash.get(clientsocket));
    feedback("java 五子棋客户端");
    feedback("/list --更新用户列表");
    feedback("/<username> <talk> --私聊");
    feedback("注意:命令必须对所有用户发送");
  }
 
  public void closeclient()
  {
    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 (ioexception exx)
    {
      exx.printstacktrace();
    }
    isclientclosed = true;
  }
 
  public void run()
  {
    datainputstream inputdata;
    synchronized (clientdatahash)
    {
      servermsgpanel.statuslabel.settext("当前连接数:" + clientdatahash.size());
    }
    try
    // 等待连接到主机的信息
      inputdata = new datainputstream(clientsocket.getinputstream());
      sendinitmsg();
      while (true)
      {
        string message = inputdata.readutf();
        dealwithmsg(message);
      }
    }
    catch (ioexception esx){}
    finally
    {
      if (!isclientclosed)
      {
        closeclient();
      }
    }
  }
}

3.开发服务器端

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import java.io.*;
import java.net.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
 
import javax.swing.jbutton;
/**
 * created by administrator on 2016/11/21.
 */
public class firserver extends frame implements actionlistener{
  jbutton clearmsgbutton = new jbutton("清空列表");
  jbutton serverstatusbutton = new jbutton("服务器状态");
  jbutton closeserverbutton = new jbutton("关闭服务器");
  panel buttonpanel = new panel();
  servermsgpanel servermsgpanel = new servermsgpanel();
  serversocket serversocket;
  hashtable clientdatahash = new hashtable(50); //将客户端套接口和输出流绑定
  hashtable clientnamehash = new hashtable(50); //将客户端套接口和客户名绑定
  hashtable chesspeerhash = new hashtable(50); //将游戏创建者和游戏加入者绑定
 
  public firserver()
  {
    super("java 五子棋服务器");
    setbackground(color.light_gray);
    buttonpanel.setlayout(new flowlayout());
    clearmsgbutton.setsize(60, 25);
    buttonpanel.add(clearmsgbutton);
    clearmsgbutton.addactionlistener(this);
    serverstatusbutton.setsize(75, 25);
    buttonpanel.add(serverstatusbutton);
    serverstatusbutton.addactionlistener(this);
    closeserverbutton.setsize(75, 25);
    buttonpanel.add(closeserverbutton);
    closeserverbutton.addactionlistener(this);
    add(servermsgpanel, borderlayout.center);
    add(buttonpanel, borderlayout.south);
 
    addwindowlistener(new windowadapter()
    {
      public void windowclosing(windowevent e)
      {
        system.exit(0);
      }
    });
    pack();
    setvisible(true);
    setsize(400, 300);
    setresizable(false);
    validate();
 
    try
    {
      createserver(4331, servermsgpanel);
    }
    catch (exception e)
    {
      e.printstacktrace();
    }
  }
 
  // 用指定端口和面板创建服务器
  public void createserver(int port, servermsgpanel servermsgpanel) throws ioexception
  {
    socket clientsocket; // 客户端套接口
    long clientaccessnumber = 1; // 连接到主机的客户数量
    this.servermsgpanel = servermsgpanel; // 设定当前主机
    try
    {
      serversocket = new serversocket(port);
      servermsgpanel.msgtextarea.settext("服务器启动于:"
          + inetaddress.getlocalhost() + ":" //djr
          + serversocket.getlocalport() + "\n");
      while (true)
      {
        // 监听客户端套接口的信息
        clientsocket = serversocket.accept();
        servermsgpanel.msgtextarea.append("已连接用户:" + clientsocket + "\n");
        // 建立客户端输出流
        dataoutputstream outputdata = new dataoutputstream(clientsocket
            .getoutputstream());
        // 将客户端套接口和输出流绑定
        clientdatahash.put(clientsocket, outputdata);
        // 将客户端套接口和客户名绑定
        clientnamehash
            .put(clientsocket, ("新玩家" + clientaccessnumber++));
        // 创建并运行服务器端线程
        firserverthread thread = new firserverthread(clientsocket,
            clientdatahash, clientnamehash, chesspeerhash, servermsgpanel);
        thread.start();
      }
    }
    catch (ioexception ex)
    {
      ex.printstacktrace();
    }
  }
 
  public void actionperformed(actionevent e)
  {
    if (e.getsource() == clearmsgbutton)
    { // 清空服务器信息
      servermsgpanel.msgtextarea.settext("");
    }
    if (e.getsource() == serverstatusbutton)
    { // 显示服务器信息
      try
      {
        servermsgpanel.msgtextarea.append("服务器信息:"
            + inetaddress.getlocalhost() + ":"
            + serversocket.getlocalport() + "\n");
      }
      catch (exception ee)
      {
        ee.printstacktrace();
      }
    }
    if (e.getsource() == closeserverbutton)
    { // 关闭服务器
      system.exit(0);
    }
  }
 
  public static void main(string args[])
  {
    firserver firserver = new firserver();
  }
}

下面开始编写客户端模块

1.开发客户端

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
 
import javax.swing.jframe;
 
import djr.chess.gui.userchatpad;
import djr.chess.gui.usercontrolpad;
import djr.chess.gui.userinputpad;
import djr.chess.gui.userlistpad;
import djr.chess.pad.firpad;
 
/**
 * created by administrator on 2016/11/21.
 */
public class firclient extends frame implements actionlistener,keylistener {
  // 客户端套接口
  socket clientsocket;
  // 数据输入流
  datainputstream inputstream;
  // 数据输出流
  dataoutputstream outputstream;
  // 用户名
  string chessclientname = null;
  // 主机地址
  string host = null;
  // 主机端口
  int port = 4331;
  // 是否在聊天
  boolean isonchat = false;
  // 是否在下棋
  boolean isonchess = false;
  // 游戏是否进行中
  boolean isgameconnected = false;
  // 是否为游戏创建者
  boolean iscreator = false;
  // 是否为游戏加入者
  boolean isparticipant = false;
  // 用户列表区
  userlistpad userlistpad = new userlistpad();
  // 用户聊天区
  userchatpad userchatpad = new userchatpad();
  // 用户操作区
  usercontrolpad usercontrolpad = new usercontrolpad();
  // 用户输入区
  userinputpad userinputpad = new userinputpad();
  // 下棋区
  firpad firpad = new firpad();
  // 面板区
  panel southpanel = new panel();
  panel northpanel = new panel();
  panel centerpanel = new panel();
  panel eastpanel = new panel();
 
  // 构造方法,创建界面
  public firclient()
  {
    super("java 五子棋客户端");
    setlayout(new borderlayout());
    host = usercontrolpad.ipinputted.gettext();
 
    eastpanel.setlayout(new borderlayout());
    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);
    usercontrolpad.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);
 
    addwindowlistener(new windowadapter()
    {
      public void windowclosing(windowevent e)
      {
        if (isonchat)
        { // 聊天中
          try
          { // 关闭客户端套接口
            clientsocket.close();
          }
          catch (exception ed){}
        }
        if (isonchess || isgameconnected)
        { // 下棋中
          try
          // 关闭下棋端口
            firpad.chesssocket.close();
          }
          catch (exception ee){}
        }
        system.exit(0);
      }
    });
 
    add(eastpanel, borderlayout.east);
    add(centerpanel, borderlayout.center);
    add(southpanel, borderlayout.south);
    pack();
    setsize(670, 560);
    setvisible(true);
    setresizable(false);
    this.validate();
  }
 
  // 按指定的ip地址和端口连接到服务器
  public boolean connecttoserver(string serverip, int serverport) throws exception
  {
    try
    {
      // 创建客户端套接口
      clientsocket = new socket(serverip, serverport);
      // 创建输入流
      inputstream = new datainputstream(clientsocket.getinputstream());
      // 创建输出流
      outputstream = new dataoutputstream(clientsocket.getoutputstream());
      // 创建客户端线程
      firclientthread clientthread = new firclientthread(this);
      // 启动线程,等待聊天信息
      clientthread.start();
      isonchat = true;
      return true;
    }
    catch (ioexception ex)
    {
      userchatpad.chattextarea
          .settext("不能连接!\n");
    }
    return false;
  }
 
  // 客户端事件处理
  public void actionperformed(actionevent e)
  {
    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 (exception ei)
      {
        userchatpad.chattextarea
            .settext("不能连接!\n");
      }
    }
    if (e.getsource() == usercontrolpad.exitbutton)
    { // 离开游戏按钮单击事件
      if (isonchat)
      { // 若用户处于聊天状态中
        try
        { // 关闭客户端套接口
          clientsocket.close();
        }
        catch (exception ed){}
      }
      if (isonchess || isgameconnected)
      { // 若用户处于游戏状态中
        try
        { // 关闭游戏端口
          firpad.chesssocket.close();
        }
        catch (exception ee){}
      }
      system.exit(0);
    }
    if (e.getsource() == usercontrolpad.joinbutton)
    { // 加入游戏按钮单击事件
      string selecteduser = (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);
              firpad.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 (exception ee)
        {
          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);
          firpad.firthread.sendmessage("/creatgame "
              + "[inchess]" + chessclientname);
        }
      }
      catch (exception ec)
      {
        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);
      }
    }
    if (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;
    }
  }
 
  public void keypressed(keyevent e)
  {
    textfield inputwords = (textfield) e.getsource();
    if (e.getkeycode() == keyevent.vk_enter)
    { // 处理回车按键事件
      if (userinputpad.userchoice.getselecteditem().equals("所有用户"))
      { // 给所有人发信息
        try
        {
          // 发送信息
          outputstream.writeutf(inputwords.gettext());
          inputwords.settext("");
        }
        catch (exception ea)
        {
          userchatpad.chattextarea
              .settext("不能连接到服务器!\n");
          userlistpad.userlist.removeall();
          userinputpad.userchoice.removeall();
          inputwords.settext("");
          usercontrolpad.connectbutton.setenabled(true);
        }
      }
      else
      { // 给指定人发信息
        try
        {
          outputstream.writeutf("/" + userinputpad.userchoice.getselecteditem()
              + " " + inputwords.gettext());
          inputwords.settext("");
        }
        catch (exception ea)
        {
          userchatpad.chattextarea
              .settext("不能连接到服务器!\n");
          userlistpad.userlist.removeall();
          userinputpad.userchoice.removeall();
          inputwords.settext("");
          usercontrolpad.connectbutton.setenabled(true);
        }
      }
    }
  }
 
  public void keytyped(keyevent e) {}
  public void keyreleased(keyevent e) {}
 
  public static void main(string args[])
  {
    firclient chessclient = new firclient();
  }
}

2.开发客户端线程

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import java.io.ioexception;
import java.util.stringtokenizer;
 
import javax.swing.defaultlistmodel;
import javax.swing.listmodel;
 
/**
 * created by administrator on 2016/11/21.
 */
public class firclientthread extends thread{
  public firclient firclient;
 
  public firclientthread(firclient firclient)
  {
    this.firclient = firclient;
  }
 
  public void dealwithmsg(string msgreceived)
  {
    if (msgreceived.startswith("/userlist "))
    { // 若取得的信息为用户列表
      stringtokenizer usertoken = new stringtokenizer(msgreceived, " ");
      int usernumber = 0;
      // 清空客户端用户列表
      firclient.userlistpad.userlist.removeall();
      // 清空客户端用户下拉框
      firclient.userinputpad.userchoice.removeall();
      // 给客户端用户下拉框添加一个选项
      firclient.userinputpad.userchoice.additem("所有用户");
      while (usertoken.hasmoretokens())
      { // 当收到的用户信息列表中存在数据时
        string user = (string) usertoken.nexttoken(" "); // 取得用户信息
        if (usernumber > 0 && !user.startswith("[inchess]"))
        { // 用户信息有效时
          firclient.userlistpad.userlist.add(user);// 将用户信息添加到用户列表中
          firclient.userinputpad.userchoice.additem(user); // 将用户信息添加到用户下拉框中
        }
        usernumber++;
      }
      firclient.userinputpad.userchoice.setselectedindex(0);// 下拉框默认选中所有人
    }
    else if (msgreceived.startswith("/yourname "))
    { // 收到的信息为用户本名时
      firclient.chessclientname = msgreceived.substring(10); // 取得用户本名
      firclient.settitle("java 五子棋客户端 " + "用户名:"
          + firclient.chessclientname); // 设置程序frame的标题
    }
    else if (msgreceived.equals("/reject"))
    { // 收到的信息为拒绝用户时
      try
      {
        firclient.firpad.statustext.settext("不能加入游戏!");
        firclient.usercontrolpad.cancelbutton.setenabled(false);
        firclient.usercontrolpad.joinbutton.setenabled(true);
        firclient.usercontrolpad.createbutton.setenabled(true);
      }
      catch (exception ef)
      {
        firclient.userchatpad.chattextarea
            .settext("cannot close!");
      }
      firclient.usercontrolpad.joinbutton.setenabled(true);
    }
    else if (msgreceived.startswith("/peer "))
    { // 收到信息为游戏中的等待时
      firclient.firpad.chesspeername = msgreceived.substring(6);
      if (firclient.iscreator)
      { // 若用户为游戏建立者
        firclient.firpad.chesscolor = 1; // 设定其为黑棋先行
        firclient.firpad.ismouseenabled = true;
        firclient.firpad.statustext.settext("黑方下...");
      }
      else if (firclient.isparticipant)
      { // 若用户为游戏加入者
        firclient.firpad.chesscolor = -1; // 设定其为白棋后性
        firclient.firpad.statustext.settext("游戏加入,等待对手.");
      }
    }
    else if (msgreceived.equals("/youwin"))
    { // 收到信息为胜利信息
      firclient.isonchess = false;
      firclient.firpad.setvicstatus(firclient.firpad.chesscolor);
      firclient.firpad.statustext.settext("对手退出");
      firclient.firpad.ismouseenabled = false;
    }
    else if (msgreceived.equals("/ok"))
    { // 收到信息为成功创建游戏
      firclient.firpad.statustext.settext("游戏创建等待对手");
    }
 
    else if (msgreceived.equals("/error"))
    { // 收到信息错误
      firclient.userchatpad.chattextarea.append("错误,退出程序.\n");
    }
    else
    {
      firclient.userchatpad.chattextarea.append(msgreceived + "\n");
      firclient.userchatpad.chattextarea.setcaretposition(
          firclient.userchatpad.chattextarea.gettext().length());
    }
  }
 
  public void run()
  {
    string message = "";
    try
    {
      while (true)
      {
        // 等待聊天信息,进入wait状态
        message = firclient.inputstream.readutf();
        dealwithmsg(message);
      }
    }
    catch (ioexception es){}
  }
}

至此,网络版五子棋就算是开发完成了。关于这么多类和包的关系如下图:

Java实现五子棋网络版

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/qq_29496057/article/details/53258880

延伸 · 阅读

精彩推荐