在使用IO流进行发送与接收时,错误过早关闭客户端发送管道导致服务器端无法将内容发回客户端。
2018.9.6 星期四下午三点十分
//客户端代码
package test01;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
static String h="";
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s=new Socket("127.0.0.1",9999);
DataOutputStream dou=new DataOutputStream(s.getOutputStream());
DataInputStream din=new DataInputStream(s.getInputStream());
BufferedReader bin1=new BufferedReader(new InputStreamReader(System.in));
String msg=bin1.readLine();
dou.writeUTF(msg);
dou.flush();
dou.close(); //此处过早关闭管道导致发生空指针
h=din.readUTF();
din.close();
}
}
//服务器端代码
package test01;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException{
ServerSocket ss=new ServerSocket(9999);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dou=new DataOutputStream(s.getOutputStream());
String msg=din.readUTF();
dou.writeUTF(msg);
dou.flush();
}
}