客户端键盘录入数据,然后发送给服务器端,不知为什么,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();
}
}
就不报错了,不知道为什么?望各位同志们看看
你的第一個客戶端程式碼中
s
是 null, 因此进入 while 中时, 导致NullPointerException
, 因此客户端直接退出了, 进而和服务器的连接没有正常关闭, 所以服务器报Exception in thread "main" java.net.SocketException: Connection reset
異常.第二個客戶端程式碼中,
while((s=br.readLine())!=null)
, 因此变量s
就不是 null, 所有就沒問題唄.