当我第一次运行下面代码的代码时它运行得很好然后我尝试添加更多代码(比如在服务器端创建缓冲输入流并尝试从客户端读取)并再次运行它给了我这个客户端异常
Exception in thread "main" java.net.SocketException: Connection reset
at java.base/sun.nio.ch.NioSocketImpl.implRead(NioSocketImpl.java:323)
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:976)
at java.base/sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:297)
at java.base/sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:339)
at java.base/sun.nio.cs.StreamDecoder.read(StreamDecoder.java:188)
at java.base/java.io.InputStreamReader.read(InputStreamReader.java:178)
at java.base/java.io.BufferedReader.fill(BufferedReader.java:161)
at java.base/java.io.BufferedReader.readLine(BufferedReader.java:329)
at java.base/java.io.BufferedReader.readLine(BufferedReader.java:396)
at client.main(client.java:20)
当我删除添加的代码并仅使用客户端的阅读器运行它时,它仍然无法工作,除非我从客户端删除输入流,否则它将无法工作,这是服务器端
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class server
{
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(8080);
Socket client = server.accept();
PrintWriter out= new PrintWriter(client.getOutputStream(),true);
out.write("dfdawdadwawdw");
}
}
这是客户端
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
import jdk.internal.jshell.tool.resources.l10n;
public class client {
public static void main(String[] args) throws Exception {
Socket java = new Socket("localhost",8080);
InputStreamReader in = new InputStreamReader(java.getInputStream());
BufferedReader bufferedreader = new BufferedReader(in);
System.out.println(bufferedreader.readLine());
}
}