Exception in thread "Thread-1" java.lang.IllegalStateException: Scanner closed at java.base/java.util.Scanner.ensureOpen(Scanner.java:1150) at java.base/java.util.Scanner.next(Scanner.java:1573) at java.base/java.util.Scanner.nextInt(Scanner.java:2258) at java.base/java.util.Scanner.nextInt(Scanner.java:2212) at my_project/myproject.Client.lambda$1(Client.java:52) at java.base/java.lang.Thread.run(Thread.java:833) java.net.SocketException: Socket closed at java.base/sun.nio.ch.NioSocketImpl.endRead(NioSocketImpl.java:248) at java.base/sun.nio.ch.NioSocketImpl.implRead(NioSocketImpl.java:327) at java.base/sun.nio.ch.NioSocketImpl.read(NioSocketImpl.java:350) at java.base/sun.nio.ch.NioSocketImpl$1.read(NioSocketImpl.java:803) at java.base/java.net.Socket$SocketInputStream.read(Socket.java:966) at java.base/java.io.InputStream.read(InputStream.java:218) at my_project/myproject.Client.lambda$0(Client.java:33) at java.base/java.lang.Thread.run(Thread.java:833)
时间: 2023-12-18 13:03:03 浏览: 156
JAVA中报错
这个错误是由于在客户端代码中的线程,Scanner对象被关闭导致的。为了解决这个问题,你可以将Scanner对象的创建和关闭操作移到主线程中。下面是修改后的代码:
```java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Client {
private static final String SERVER_IP = "localhost";
private static final int SERVER_PORT = 8888;
private String username;
public void start() {
try {
Socket socket = new Socket(SERVER_IP, SERVER_PORT);
System.out.println("成功连接服务器");
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
// 发送消息给服务器
new Thread(() -> {
try {
Scanner scanner = new Scanner(System.in);
while (true) {
String message = scanner.nextLine();
outputStream.write(message.getBytes());
outputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
// 接收服务器发送的消息
try {
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > 0) {
String message = new String(buffer, 0, len);
System.out.println("收到服务器消息:" + message);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Client client = new Client();
client.start();
}
}
```
在修改后的代码中,我们将接收服务器发送消息的逻辑移到了主线程中,并在最后关闭了Socket连接。这样就避免了在子线程中关闭Scanner对象和Socket连接的问题。
阅读全文