标签:style blog color io os ar java sp 数据
今天在学习java socket通信部分的时候,写了一个demo测试。但是写入数据后一直接收不到,纠结半天,终于发现是输入流没有调用flush()刷新。
package SocketTests; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; class Server { public static void main(String[] args) throws IOException { new Server(new ServerSocket(3001)).run(); } private ServerSocket server; Socket s=null; public Server(ServerSocket server) { super(); this.server = server; } public void run() { try { while(true) { s=server.accept(); InputStream is=s.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); char[]buf=new char[1024]; int i; while((i=br.read(buf))>0) System.out.println("server receive: "+new String(buf)); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { if(server!=null) server.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package SocketTests; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class TCPTest { public static void main(String[] args) throws IOException { new Client(new Socket(InetAddress.getLocalHost(),3001)).run(); } } class Client { private Socket client; public Client(Socket client) { super(); this.client = client; } public void run() { try { OutputStream os=client.getOutputStream(); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os)); Scanner scanner=new Scanner(System.in); String str; while(scanner.hasNextLine()) { str=scanner.nextLine(); bw.write(str); System.out.println("client write: "+str); bw.flush();//刷新流的缓冲,没有这行代码,数据没有写进,服务端调用bw.readLine()将一直堵塞 } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { if(client!=null) client.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
在学习IO流的时候,我写的例子中输入流在写入完成后直接调用了close()方法关闭,流在关闭前会自动刷新!而上面这个例子中,客户端写入数据后,并没有关闭,而是在等待下一次输入;这样,当服务器短调用br.readLine()的时候,一直堵塞,所以读不到任何数据!!
标签:style blog color io os ar java sp 数据
原文地址:http://www.cnblogs.com/twobrothers/p/4040669.html