五子棋网络版java
时间: 2024-01-12 16:21:54 浏览: 89
很高兴听到你对Java五子棋网络版的兴趣!下面是一个简单的Java五子棋网络版的实现示例:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器已启动,等待客户端连接...");
Socket socket = serverSocket.accept();
System.out.println("客户端已连接!");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
String message;
while ((message = reader.readLine()) != null) {
System.out.println("客户端消息:" + message);
writer.println("服务器收到消息:" + message);
}
reader.close();
writer.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
System.out.println("已连接到服务器!");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
String message;
while ((message = consoleReader.readLine()) != null) {
writer.println(message);
System.out.println("服务器回复:" + reader.readLine());
}
reader.close();
writer.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这是一个简单的五子棋网络版的实现,其中Server类用于启动服务器,Client类用于启动客户端。服务器监听8888端口,客户端连接到服务器后可以发送消息并接收服务器的回复。
阅读全文