Java network programming-guessing game
猜数字游戏
游戏的规则如下:
当客户端第一次连接到服务器端时,服务器端生产一个【0,50】之间的随机数字,然后客户端输入数字来猜该数字,每次客户端输入数字以后,发送给服务器端,服务器端判断该客户端发送的数字和随机数字的关系,并反馈比较结果,客户端总共有5次猜的机会,猜中时提示猜中,当输入”quit”时结束程序。
为了实现这个游戏,我写了三个类,客户端,服务器端以及一个实现多客户端的线程类。
该程序是以前学习 Java 网络编程时所写(写于2013年5月),还有很多地方有待完善,可以参考牛人的文章。
客户端类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class TCPGameClient
{
static BufferedReader br = null;
static Socket socket = null;
static InputStream is = null;
static OutputStream os = null;
final static String HOST = "localhost";
final static int PORT = 10008;
public final static String EQUALS = "E" ;
public final static String GREATER = "G";
public final static String LESSER = "L";
public final static String NEXT = "NEXT";
public static void main(String[] args) throws Exception
{
//初始化socket,输入输出流
init();
System.out.println("The Game Begain!");
byte[] bufResult = new byte[10];
while(true)
{
//获取server产生的随机数
String strDate = new String(receive());
System.out.println("Please enter your guess:(If you want to end,input quit)");
//从控制板获取输入字符
String str = br.readLine();
if(isQuit(str))
{
System.out.println("Bye!");
break;
}
//client端控制猜谜次数
int count = 5;
while(count > 0)
{
//向 server端发送client 猜的数字
send(str.getBytes());
//接收来自server的对比后的反馈
bufResult = receive();
String result = new String(bufResult);
if(EQUALS.equalsIgnoreCase(result))
{
System.out.println("Congratulations! You are rgiht.");
send(NEXT.getBytes());
break;
} else if(GREATER.equalsIgnoreCase(result))
{
count --;
System.out.println("Greater!");
System.out.println("You have " + count + " chances left.");
} else if(LESSER.equalsIgnoreCase(result))
{
count --;
System.out.println("Lesser!");
System.out.println("You have " + count + " chances left.");
} else{;}
//猜谜次数未到?继续
if(count > 0)
{
System.out.println("Please enter your guess:");
str = br.readLine();
}
//猜谜次数已到,还没猜出?打印谜底,同时告诉server开始下一轮猜谜游戏
if(count == 0)
{
System.out.println("The right answer is: " + strDate);
send(NEXT.getBytes());
}
}
}
close();
}
private static void init() throws IOException
{
br = new BufferedReader(new InputStreamReader(System.in));
socket = new Socket(HOST, PORT);
is = socket.getInputStream();
os = socket.getOutputStream();
}
private static byte[] receive() throws IOException
{
byte[] buf = new byte[10];
int len = is.read(buf);
byte[] receiveData = new byte[len];
System.arraycopy(buf, 0, receiveData, 0, len);
return receiveData;
}
private static void send(byte[] b) throws IOException
{
os.write(b);
}
private static boolean isQuit(String str)
{
boolean flag = false;
if(null == str)
flag = false;
else
{
if("quit".equalsIgnoreCase(str))
{
flag = true;
}
else
{
flag = false;
}
}
return flag;
}
private static void close() throws Exception
{
socket.close();
is.close();
os.close();
}
}
服务器类
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPGameServer
{
static ServerSocket serverSocket = null;
final static int PORT = 10008;
public static void main(String[] args) throws IOException
{
try
{
//初始化ServerSocke,开始监听
serverSocket = new ServerSocket(PORT);
System.out.println("The Server started.");
while(true)
{
Socket socket = serverSocket.accept();
new TCPGameThread(socket).start();
}
}
catch (Exception e)
{
e.printStackTrace();
}
serverSocket.close();
}
}
线程类
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Random;
public class TCPGameThread extends Thread
{
Socket socket = null;
InputStream is = null;
OutputStream os = null;
public final static String EQUALS = "E" ;
public final static String GREATER = "G";
public final static String LESSER = "L";
public final static String NEXT = "NEXT";
public TCPGameThread(Socket socket) throws IOException
{
this.socket = socket;
is = this.socket.getInputStream();
os = this.socket.getOutputStream();
}
@Override
public void run()
{
try
{
while(true)
{
//产生一个在[0,50]之间的随机数
int randomData = -1;
randomData = createRandom(0, 50);
String str = String.valueOf(randomData);
System.out.println("random data: " + randomData);
try
{
//将该随机数发送给client端
send(str.getBytes());
}catch(Exception e){
break;
}
while(true)
{
try
{
//接收来自client端的猜数
byte[] b = receive();
String strReceive = new String(b, 0, b.length);
System.out.println("strReceive: " + strReceive);
if(isNext(strReceive))break;
//比较谜底和猜数之间的关系并反馈比较结果
String checkResult = checkClientData(randomData, strReceive);
send(checkResult.getBytes());
}
catch (IOException e)
{
break;
}
}
}
}
catch (Exception e)
{
try
{
close();
}
catch (Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
private byte[] receive() throws IOException
{
byte[] buf = new byte[10];
int len = is.read(buf);
byte[] receiveData = new byte[len];
System.arraycopy(buf, 0, receiveData, 0, len);
return receiveData;
}
private void send(byte[] b) throws IOException
{
os.write(b);
}
private int createRandom(int start, int end)
{
Random r = new Random();
return r.nextInt(end - start + 1) + start;
}
private String checkClientData(int randomData, String data)
{
String checkResult = null;
int buf = Integer.parseInt(data);
if(buf == randomData)
{checkResult = EQUALS;}
else if(buf > randomData)
{checkResult = GREATER;}
else if(buf < randomData)
{checkResult = LESSER;}
else
{;}
return checkResult ;
}
private void close() throws Exception
{
socket.close();
is.close();
os.close();
}
private static boolean isNext(String str)
{
boolean flag = false;
if(null == str)
flag = false;
else
{
if(NEXT.equalsIgnoreCase(str))
{
flag = true;
}
else
{
flag = false;
}
}
return flag;
}
}
Java network programming-guessing game的更多相关文章
- Andrew's Blog / 《Network Programming with Go》学习笔记
第一章: Architecture(体系结构) Protocol Layers(协议层) ISO OSI Protocol 每层的功能: 网络层提供交换及路由技术 传输层提供了终端系统之间的数据透明传 ...
- 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 ...
- python network programming tutorial
关于网络编程以及socket 等一些概念和函数介绍就不再重复了,这里示例性用python 编写客户端和服务器端. 一.最简单的客户端流程: 1. Create a socket 2. Connect ...
- Fast portable non-blocking network programming with Libevent
Fast portable non-blocking network programming with Libevent Fast portable non-blocking network prog ...
- Neural Network Programming - Deep Learning with PyTorch with deeplizard.
PyTorch Prerequisites - Syllabus for Neural Network Programming Series PyTorch先决条件 - 神经网络编程系列教学大纲 每个 ...
- Python socket – network programming tutorial
原文:https://www.binarytides.com/python-socket-programming-tutorial/ --------------------------------- ...
- [C1W2] Neural Networks and Deep Learning - Basics of Neural Network programming
第二周:神经网络的编程基础(Basics of Neural Network programming) 二分类(Binary Classification) 这周我们将学习神经网络的基础知识,其中需要 ...
- 吴恩达《深度学习》-第一门课 (Neural Networks and Deep Learning)-第二周:(Basics of Neural Network programming)-课程笔记
第二周:神经网络的编程基础 (Basics of Neural Network programming) 2.1.二分类(Binary Classification) 二分类问题的目标就是习得一个分类 ...
- 课程一(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 ...
- Java 8 实战 P3 Effective Java 8 programming
目录 Chapter 8. Refactoring, testing, and debugging Chapter 9. Default methods Chapter 10. Using Optio ...
随机推荐
- MySQL复制 -- 应用场景
本文行文路径如下: 什么是复制?复制是怎么工作的?复制有哪几种表现形式?复制能解决那些问题?业界有哪些数据同步解决方案? 什么是复制? 官方解释道:Replication enables data f ...
- OpenGL 加载DDS文件(压缩纹理)
想必很多人都见过DDS这种文件,它是一个“图片文件”,如果你安装了某些看图软件,你可以直接双击打开它来进行预览. 那么,这种DDS文件和我们常见的TGA/PNG之类的文件有何不同呢? DDS和TGA/ ...
- MySQL主键和外键使用及说明
摘自网上一个经典的例子:大哥和小弟 一.外键约束 MySQL通过外键约束来保证表与表之间的数据的完整性和准确性. 外键的使用条件: 1.两个表必须是InnoDB表,MyISAM表暂时不支持外键(据说 ...
- https的通信过程
https的特点 1. https有 握手阶段 和 请求阶段2. 握手阶段 使用 非对称加密算法 请求阶段 使用 对称加密算法3. 保证数据的完整性使用数字签名4. 握手阶段有两组非对称加密,数字证书 ...
- 解题:ZJOI 2006 书架
题面 学习了如何在维护序列的平衡树上查找某个数:按初始的顺序定个权值,然后每次找那个权值的DFS序即可.具体实现就是不停往上跳,然后是父亲的右儿子就加上父亲的左儿子,剩下的就是继续熟悉无旋树堆 #in ...
- mac pro电脑怎么安装rabbitmq
第一:依次执行以下命令: 1. /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/inst ...
- json数据的格式
JSON的具体形式 1.对象是一个无序的“‘名称/值’对”集合.一个对象以“{”开始,以“}”结束.每个“名称”后跟一个“:”,“‘名称/值’对”之间使用“,”分隔. 举个例子: { name:&qu ...
- 安装好dashboard 登录出现错误
验证发生错误.请稍后再试一次. While turning SELinux off certainly does the trick, it is somewhat like using a sled ...
- bzoj 2530 [Poi2011]Party 构造
2530: [Poi2011]Party Time Limit: 10 Sec Memory Limit: 128 MBSec Special JudgeSubmit: 364 Solved: ...
- 赤池信息量准则 ( Akaike information criterion)
sklearn实战-乳腺癌细胞数据挖掘(博主亲自录制视频) https://study.163.com/course/introduction.htm?courseId=1005269003& ...