客户端键盘录入数据,然后发送给服务器端,不知为什么,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();
}
}
就不报错了,不知道为什么?望各位同志们看看
Dalam kod pelanggan pertama anda,
s
adalah batal, jadi apabila memasukkan sementara,NullPointerException
disebabkan, jadi pelanggan keluar terus, dan sambungan dengan pelayan tidak ditutup seperti biasa, jadi pelayan melaporkanException in thread "main" java.net.SocketException: Connection reset
Pengecualian.Dalam kod pelanggan kedua,
while((s=br.readLine())!=null)
, jadi pembolehubahs
bukan batal, jadi semuanya baik-baik saja.