java socket小游戏_Java Socket实现猜数字小游戏
时间: 2023-07-14 07:13:42 浏览: 134
Java Socket 实现猜数字小游戏
本文介绍如何使用 Java Socket 编写简单的猜数字小游戏,实现多人在线游戏。
1. 服务器端实现
服务器端实现主要包括以下几个步骤:
1.1 建立 ServerSocket
```java
ServerSocket serverSocket = new ServerSocket(port);
```
1.2 等待客户端连接
```java
Socket socket = serverSocket.accept();
```
1.3 获取输入输出流
```java
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
```
1.4 生成随机数并发送给客户端
```java
int number = (int) (Math.random() * 100);
outputStream.write(number);
```
1.5 接收客户端猜测的数字并判断是否正确
```java
int guess = inputStream.read();
if (guess == number) {
outputStream.write(1); // 猜测正确
} else {
outputStream.write(0); // 猜测错误
}
```
完整代码如下:
```java
public class GuessNumberServer {
public static void main(String[] args) throws IOException {
int port = 8888;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("服务器已启动,等待客户端连接...");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("客户端已连接:" + socket.getInetAddress().getHostAddress());
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
int number = (int) (Math.random() * 100);
outputStream.write(number);
int guess = inputStream.read();
if (guess == number) {
outputStream.write(1); // 猜测正确
} else {
outputStream.write(0); // 猜测错误
}
socket.close();
}
}
}
```
2. 客户端实现
客户端实现主要包括以下几个步骤:
2.1 建立 Socket 连接
```java
Socket socket = new Socket(serverIp, port);
```
2.2 获取输入输出流
```java
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
```
2.3 接收服务器发送的随机数并猜测
```java
int number = inputStream.read();
System.out.println("服务器生成的随机数是:" + number);
Scanner scanner = new Scanner(System.in);
System.out.print("请输入猜测的数字(0-99):");
int guess = scanner.nextInt();
outputStream.write(guess);
```
2.4 接收服务器返回的猜测结果并输出
```java
int result = inputStream.read();
if (result == 1) {
System.out.println("恭喜猜测正确!");
} else {
System.out.println("很遗憾猜测错误!");
}
```
完整代码如下:
```java
public class GuessNumberClient {
public static void main(String[] args) throws IOException {
String serverIp = "127.0.0.1";
int port = 8888;
Socket socket = new Socket(serverIp, port);
System.out.println("已连接服务器:" + serverIp);
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
int number = inputStream.read();
System.out.println("服务器生成的随机数是:" + number);
Scanner scanner = new Scanner(System.in);
System.out.print("请输入猜测的数字(0-99):");
int guess = scanner.nextInt();
outputStream.write(guess);
int result = inputStream.read();
if (result == 1) {
System.out.println("恭喜猜测正确!");
} else {
System.out.println("很遗憾猜测错误!");
}
socket.close();
}
}
```
3. 运行效果
启动服务器端后,等待客户端连接:
```
服务器已启动,等待客户端连接...
```
启动客户端后,输入猜测的数字:
```
已连接服务器:127.0.0.1
服务器生成的随机数是:14
请输入猜测的数字(0-99):50
很遗憾猜测错误!
```
再次运行客户端,输入猜测的数字:
```
已连接服务器:127.0.0.1
服务器生成的随机数是:92
请输入猜测的数字(0-99):92
恭喜猜测正确!
```
以上就是使用 Java Socket 实现猜数字小游戏的详细步骤。
阅读全文