客户端键盘录入数据,然后发送给服务器端,不知为什么,br.readLine()方法的位置不同,就可能出现服务器端报错
客户端代码:
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket client=new Socket("192.168.1.109",8888);
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
BufferedWriter bw=new BufferedWriter(
new OutputStreamWriter(client.getOutputStream()));
String s=null;
while(true)
{
if(s.equals("886"))
break;
s=br.readLine();
bw.write(s);
bw.newLine();
bw.flush();
}
client.close();
br.close();
bw.close();
}
}
服务器代码:
public class Server {
public static void main(String[] args) throws IOException {
// TODO 自动生成的方法存根
ServerSocket ss=new ServerSocket(8888);
Socket s=ss.accept();
BufferedReader br=new BufferedReader(
new InputStreamReader(s.getInputStream()));
String str=null;
while((str=br.readLine())!=null)
{
System.out.println(str);
}
}
}
报错信息:
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at com.znfsy.www.tcp.Server.main(Server.java:18)
而假如把客户端的代码改成如下:
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket client=new Socket("192.168.1.109",8888);
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
BufferedWriter bw=new BufferedWriter(
new OutputStreamWriter(client.getOutputStream()));
String s=null;
while((s=br.readLine())!=null)
{
if(s.equals("886"))
break;
bw.write(s);
bw.newLine();
bw.flush();
}
client.close();
br.close();
bw.close();
}
}
就不报错了,不知道为什么?望各位同志们看看
ringa_lee2017-04-18 10:25:12
첫 번째 클라이언트 코드에서 s
이 null이므로 while을 입력하면 NullPointerException
이 발생하여 클라이언트가 직접 종료되고 서버와의 연결이 정상적으로 닫히지 않아 서버에서 <🎜를 보고합니다. > 예외입니다.Exception in thread "main" java.net.SocketException: Connection reset
에서는 while((s=br.readLine())!=null)
변수가 null이 아니므로 모든 것이 정상입니다.s