Java中的socket编程使用BufferedReader和BufferedWriter会出现的问题

用socket通讯写出客户端和服务器端的通讯,要求客户发送数据后能够回显相同的数据。

 

如果使用BufferedWriter 不加newline()和flush()的话,
服务端BufferedReader 的readline()方法就读取不到msg,会一直阻塞下去。

但是使用BufferedReader读取本地文本文件,尽管只有一行数据,也能正常读取。

下面是我编写的客户端的代码:

public class ClientSocket {
	public static void main(String[] args) throws Exception {
		System.out.println("我是客户端");
		Socket s = new Socket("localhost", 8899);
		BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//		PrintStream ps = new PrintStream(s.getOutputStream());
		Scanner input = new Scanner(System.in);
		String msg = input.nextLine();
		while(true) {
//			ps.println(msg);
			bw.write(msg);
			//在这里被坑到了,如果使用BufferedWriter 不加newline()和flush()的话,
			//服务端BufferedReader 的readline()方法就读取不到msg,会一直阻塞下去。
			bw.newLine();
			bw.flush();
			msg = br.readLine();
			System.out.println("服务器:" + msg);
			if("stop".equals(msg)) {
				break;
			}
			msg = input.nextLine();
		}
		
		br.close();
//		ps.close();
		bw.close();
		s.close();
	}
}

服务端代码如下:(如果使用打印流PrintStream的话,就能避免上面遇到的麻烦了)

public class ServerSocket1 {
	public static void main(String[] args) throws Exception {
		System.out.println("我是服务器");
		ServerSocket ss = new ServerSocket(8899);
		Socket s = ss.accept();
		
		BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
//		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
		PrintStream ps = new PrintStream(s.getOutputStream());
		String msg = br.readLine();
		while(true) {
			System.out.println("客户端:" + msg);
			ps.println(msg);
			if("stop".equals(msg)) {
				break;
			}
			msg = br.readLine();
		}
		ps.close();
		br.close();
		s.close();
	}
}

 

你可能感兴趣的:(随笔,Java)