Java多线程Socket操作猜数游戏样例
时间: 2023-06-29 18:18:00 浏览: 132
下面是一个简单的 Java 多线程 Socket 操作猜数游戏的示例:
```java
import java.io.*;
import java.net.*;
public class GuessingGameServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("Server started!");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected!");
Thread gameThread = new Thread(new Game(clientSocket));
gameThread.start();
}
}
}
class Game implements Runnable {
private Socket clientSocket;
public Game(Socket clientSocket) {
this.clientSocket = clientSocket;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
int randomNumber = (int) (Math.random() * 100) + 1;
out.println("I'm thinking of a number between 1 and 100. Try to guess it!");
int guess;
do {
guess = Integer.parseInt(in.readLine());
if (guess < randomNumber) {
out.println("Too low. Guess again.");
} else if (guess > randomNumber) {
out.println("Too high. Guess again.");
}
} while (guess != randomNumber);
out.println("Congratulations! You guessed the number!");
clientSocket.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
```
这个示例程序会监听 8888 端口,当有客户端连接时,就会创建一个新的线程来处理游戏。在游戏中,服务器会生成一个 1 到 100 的随机数,然后一直等待客户端猜测,直到猜中为止。每次猜测后,服务器会给出相应的提示。当游戏结束时,服务器会关闭与客户端的连接。
阅读全文