猜数字游戏

游戏的规则如下:

当客户端第一次连接到服务器端时,服务器端生产一个【0,50】之间的随机数字,然后客户端输入数字来猜该数字,每次客户端输入数字以后,发送给服务器端,服务器端判断该客户端发送的数字和随机数字的关系,并反馈比较结果,客户端总共有5次猜的机会,猜中时提示猜中,当输入”quit”时结束程序。
为了实现这个游戏,我写了三个类,客户端,服务器端以及一个实现多客户端的线程类。

该程序是以前学习 Java 网络编程时所写(写于2013年5月),还有很多地方有待完善,可以参考牛人的文章

客户端类

  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. import java.io.OutputStream;
  6. import java.net.Socket;
  7. public class TCPGameClient
  8. {
  9. static BufferedReader br = null;
  10. static Socket socket = null;
  11. static InputStream is = null;
  12. static OutputStream os = null;
  13. final static String HOST = "localhost";
  14. final static int PORT = 10008;
  15. public final static String EQUALS = "E" ;
  16. public final static String GREATER = "G";
  17. public final static String LESSER = "L";
  18. public final static String NEXT = "NEXT";
  19. public static void main(String[] args) throws Exception
  20. {
  21. //初始化socket,输入输出流
  22. init();
  23. System.out.println("The Game Begain!");
  24. byte[] bufResult = new byte[10];
  25. while(true)
  26. {
  27. //获取server产生的随机数
  28. String strDate = new String(receive());
  29. System.out.println("Please enter your guess:(If you want to end,input quit)");
  30. //从控制板获取输入字符
  31. String str = br.readLine();
  32. if(isQuit(str))
  33. {
  34. System.out.println("Bye!");
  35. break;
  36. }
  37. //client端控制猜谜次数
  38. int count = 5;
  39. while(count > 0)
  40. {
  41. //向 server端发送client 猜的数字
  42. send(str.getBytes());
  43. //接收来自server的对比后的反馈
  44. bufResult = receive();
  45. String result = new String(bufResult);
  46. if(EQUALS.equalsIgnoreCase(result))
  47. {
  48. System.out.println("Congratulations! You are rgiht.");
  49. send(NEXT.getBytes());
  50. break;
  51. } else if(GREATER.equalsIgnoreCase(result))
  52. {
  53. count --;
  54. System.out.println("Greater!");
  55. System.out.println("You have " + count + " chances left.");
  56. } else if(LESSER.equalsIgnoreCase(result))
  57. {
  58. count --;
  59. System.out.println("Lesser!");
  60. System.out.println("You have " + count + " chances left.");
  61. } else{;}
  62. //猜谜次数未到?继续
  63. if(count > 0)
  64. {
  65. System.out.println("Please enter your guess:");
  66. str = br.readLine();
  67. }
  68. //猜谜次数已到,还没猜出?打印谜底,同时告诉server开始下一轮猜谜游戏
  69. if(count == 0)
  70. {
  71. System.out.println("The right answer is: " + strDate);
  72. send(NEXT.getBytes());
  73. }
  74. }
  75. }
  76. close();
  77. }
  78. private static void init() throws IOException
  79. {
  80. br = new BufferedReader(new InputStreamReader(System.in));
  81. socket = new Socket(HOST, PORT);
  82. is = socket.getInputStream();
  83. os = socket.getOutputStream();
  84. }
  85. private static byte[] receive() throws IOException
  86. {
  87. byte[] buf = new byte[10];
  88. int len = is.read(buf);
  89. byte[] receiveData = new byte[len];
  90. System.arraycopy(buf, 0, receiveData, 0, len);
  91. return receiveData;
  92. }
  93. private static void send(byte[] b) throws IOException
  94. {
  95. os.write(b);
  96. }
  97. private static boolean isQuit(String str)
  98. {
  99. boolean flag = false;
  100. if(null == str)
  101. flag = false;
  102. else
  103. {
  104. if("quit".equalsIgnoreCase(str))
  105. {
  106. flag = true;
  107. }
  108. else
  109. {
  110. flag = false;
  111. }
  112. }
  113. return flag;
  114. }
  115. private static void close() throws Exception
  116. {
  117. socket.close();
  118. is.close();
  119. os.close();
  120. }
  121. }

服务器类

  1. import java.io.IOException;
  2. import java.net.ServerSocket;
  3. import java.net.Socket;
  4. public class TCPGameServer
  5. {
  6. static ServerSocket serverSocket = null;
  7. final static int PORT = 10008;
  8. public static void main(String[] args) throws IOException
  9. {
  10. try
  11. {
  12. //初始化ServerSocke,开始监听
  13. serverSocket = new ServerSocket(PORT);
  14. System.out.println("The Server started.");
  15. while(true)
  16. {
  17. Socket socket = serverSocket.accept();
  18. new TCPGameThread(socket).start();
  19. }
  20. }
  21. catch (Exception e)
  22. {
  23. e.printStackTrace();
  24. }
  25. serverSocket.close();
  26. }
  27. }

线程类

  1. import java.io.IOException;
  2. import java.io.InputStream;
  3. import java.io.OutputStream;
  4. import java.net.Socket;
  5. import java.util.Random;
  6. public class TCPGameThread extends Thread
  7. {
  8. Socket socket = null;
  9. InputStream is = null;
  10. OutputStream os = null;
  11. public final static String EQUALS = "E" ;
  12. public final static String GREATER = "G";
  13. public final static String LESSER = "L";
  14. public final static String NEXT = "NEXT";
  15. public TCPGameThread(Socket socket) throws IOException
  16. {
  17. this.socket = socket;
  18. is = this.socket.getInputStream();
  19. os = this.socket.getOutputStream();
  20. }
  21. @Override
  22. public void run()
  23. {
  24. try
  25. {
  26. while(true)
  27. {
  28. //产生一个在[0,50]之间的随机数
  29. int randomData = -1;
  30. randomData = createRandom(0, 50);
  31. String str = String.valueOf(randomData);
  32. System.out.println("random data: " + randomData);
  33. try
  34. {
  35. //将该随机数发送给client端
  36. send(str.getBytes());
  37. }catch(Exception e){
  38. break;
  39. }
  40. while(true)
  41. {
  42. try
  43. {
  44. //接收来自client端的猜数
  45. byte[] b = receive();
  46. String strReceive = new String(b, 0, b.length);
  47. System.out.println("strReceive: " + strReceive);
  48. if(isNext(strReceive))break;
  49. //比较谜底和猜数之间的关系并反馈比较结果
  50. String checkResult = checkClientData(randomData, strReceive);
  51. send(checkResult.getBytes());
  52. }
  53. catch (IOException e)
  54. {
  55. break;
  56. }
  57. }
  58. }
  59. }
  60. catch (Exception e)
  61. {
  62. try
  63. {
  64. close();
  65. }
  66. catch (Exception e1)
  67. {
  68. // TODO Auto-generated catch block
  69. e1.printStackTrace();
  70. }
  71. }
  72. }
  73. private byte[] receive() throws IOException
  74. {
  75. byte[] buf = new byte[10];
  76. int len = is.read(buf);
  77. byte[] receiveData = new byte[len];
  78. System.arraycopy(buf, 0, receiveData, 0, len);
  79. return receiveData;
  80. }
  81. private void send(byte[] b) throws IOException
  82. {
  83. os.write(b);
  84. }
  85. private int createRandom(int start, int end)
  86. {
  87. Random r = new Random();
  88. return r.nextInt(end - start + 1) + start;
  89. }
  90. private String checkClientData(int randomData, String data)
  91. {
  92. String checkResult = null;
  93. int buf = Integer.parseInt(data);
  94. if(buf == randomData)
  95. {checkResult = EQUALS;}
  96. else if(buf > randomData)
  97. {checkResult = GREATER;}
  98. else if(buf < randomData)
  99. {checkResult = LESSER;}
  100. else
  101. {;}
  102. return checkResult ;
  103. }
  104. private void close() throws Exception
  105. {
  106. socket.close();
  107. is.close();
  108. os.close();
  109. }
  110. private static boolean isNext(String str)
  111. {
  112. boolean flag = false;
  113. if(null == str)
  114. flag = false;
  115. else
  116. {
  117. if(NEXT.equalsIgnoreCase(str))
  118. {
  119. flag = true;
  120. }
  121. else
  122. {
  123. flag = false;
  124. }
  125. }
  126. return flag;
  127. }
  128. }

Java network programming-guessing game的更多相关文章

  1. Andrew's Blog / 《Network Programming with Go》学习笔记

    第一章: Architecture(体系结构) Protocol Layers(协议层) ISO OSI Protocol 每层的功能: 网络层提供交换及路由技术 传输层提供了终端系统之间的数据透明传 ...

  2. Professional iOS Network Programming Connecting the Enterprise to the iPhone and iPad

    Book Description Learn to develop iPhone and iPad applications for networked enterprise environments ...

  3. python network programming tutorial

    关于网络编程以及socket 等一些概念和函数介绍就不再重复了,这里示例性用python 编写客户端和服务器端. 一.最简单的客户端流程: 1. Create a socket 2. Connect ...

  4. Fast portable non-blocking network programming with Libevent

    Fast portable non-blocking network programming with Libevent Fast portable non-blocking network prog ...

  5. Neural Network Programming - Deep Learning with PyTorch with deeplizard.

    PyTorch Prerequisites - Syllabus for Neural Network Programming Series PyTorch先决条件 - 神经网络编程系列教学大纲 每个 ...

  6. Python socket – network programming tutorial

    原文:https://www.binarytides.com/python-socket-programming-tutorial/ --------------------------------- ...

  7. [C1W2] Neural Networks and Deep Learning - Basics of Neural Network programming

    第二周:神经网络的编程基础(Basics of Neural Network programming) 二分类(Binary Classification) 这周我们将学习神经网络的基础知识,其中需要 ...

  8. 吴恩达《深度学习》-第一门课 (Neural Networks and Deep Learning)-第二周:(Basics of Neural Network programming)-课程笔记

    第二周:神经网络的编程基础 (Basics of Neural Network programming) 2.1.二分类(Binary Classification) 二分类问题的目标就是习得一个分类 ...

  9. 课程一(Neural Networks and Deep Learning),第二周(Basics of Neural Network programming)—— 4、Logistic Regression with a Neural Network mindset

    Logistic Regression with a Neural Network mindset Welcome to the first (required) programming exerci ...

  10. Java 8 实战 P3 Effective Java 8 programming

    目录 Chapter 8. Refactoring, testing, and debugging Chapter 9. Default methods Chapter 10. Using Optio ...

随机推荐

  1. Jstack、Jmap命令简单使用

    TOMCAT_ID为tomcat的进程号. 1.使用jstack查看jvm堆栈信息. /bin/ TOMCAT_ID:无法输出到单独的文件中,只能在tomcat的启动文件中打印相关的堆栈信息. jst ...

  2. DAVY的神龙帕夫——读者的心灵故事|十二橄榄枝的传说

    再次听Puff的时候我想起了Davy. 文理分班后我坐到了他后面.Davy天生一头黄毛,黑头发”not even one”.上课时他若不是肆无忌惮地舒开四肢呼呼大睡,便是如受惊一般伸长他的细脖子,直挺 ...

  3. 51nod 1526 分配笔名(字典树+贪心)

    题意: 班里有n个同学.老师为他们选了n个笔名.现在要把这些笔名分配给每一个同学,每一个同学分配到一个笔名,每一个笔名必须分配给某个同学.现在定义笔名和真名之间的相关度是他们之间的最长公共前缀.设笔名 ...

  4. 【BZOJ2216】Lightning Conductor(动态规划)

    [BZOJ2216]Lightning Conductor(动态规划) 题面 BZOJ,然而是权限题 洛谷 题解 \(\sqrt {|i-j|}\)似乎没什么意义,只需要从前往后做一次再从后往前做一次 ...

  5. NOIP模拟

    1.要选一个{1,2,...n}的子集使得假如a和b在所选集合里且(a+b)/2∈{1,2,...n}那么(a+b)/2也在所选集合里 f[i]=2*f[i-1]-f[i-2]+g[i] g[n]:选 ...

  6. 洛谷P4609 [FJOI2016]建筑师 【第一类斯特林数】

    题目链接 洛谷P4609 题解 感性理解一下: 一神带\(n\)坑 所以我们只需将除了\(n\)外的\(n - 1\)个元素分成\(A + B - 2\)个集合,每个集合选出最大的在一端,剩余进行排列 ...

  7. Hive(六)hive执行过程实例分析与hive优化策略

    一.Hive 执行过程实例分析 1.join 对于 join 操作:SELECT pv.pageid, u.age FROM page_view pv JOIN user u ON (pv.useri ...

  8. mysql数据库----索引补充

    1.索引 索引是表的目录,在查找内容之前可以先在目录中查找索引位置,以此快速定位查询数据.对于索引,会保存在额外的文件中. 2.索引种类 普通索引:仅加速查询 唯一索引:加速查询 + 列值唯一(可以有 ...

  9. Hdu1542 Atlantis

    Atlantis Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Su ...

  10. 2018-2019 ACM-ICPC 焦作赛区 部分题解

    题目链接:https://codeforces.com/gym/102028 B. Ultraman vs. Aodzilla and Bodzilla 题意: 两只怪兽,它们的生命和攻击分别为hpA ...