日期:2014-05-20  浏览次数:20747 次

关于BufferedReader类在客户端与服务器端通信的问题
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class Client {
public static final int LISTEN_PORT=5473;
public static final String IP="127.0.0.1";

public static void main(String arg[])
{
Socket s=null;
String str="hello !I'm coming!!";
BufferedWriter bw=null;
BufferedReader br=null;
/*InetAddress ia=null;
try
{
ia=InetAddress.getByName(IP);
}catch(UnknownHostException e)
{
e.printStackTrace();
}*/

try
{
s=new Socket(IP,LISTEN_PORT);
bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
bw.write(str,0,str.length());
bw.flush();
System.out.println("stay !!!!!");
System.out.println(br.readLine());
}catch(IOException e)
{
e.printStackTrace();
}
finally
{
if (s!=null)
try {
s.close();
} catch (IOException e) {

e.printStackTrace();
}
}
}

}

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
public static final int LISTEN_PORT=5473;

public static void main(String arg[])
{
ServerSocket ss=null;
Socket s=null;
BufferedReader br=null;
BufferedWriter bw=null;

try 
{
ss=new ServerSocket(LISTEN_PORT);
s=ss.accept();
System.out.println("a connect have come");
br =new BufferedReader(new InputStreamReader(s.getInputStream()));
bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String str=br.readLine();
System.out.println("stop here!!!");
System.out.println(str);
/*br=new BufferedReader(new InputStreamReader(System.in));
str=br.readLine();*/
str="weclome!!";

bw.write(str,0,str.length());
bw.flush();
} catch (IOException e) 
{
e.printStackTrace();
}
finally
{
if (s!=null)
try {
s.close();
} catch (IOException e) {

e.printStackTrace();
}
}
}
}
以上分别是客户端与服务器端的代码,执行后,服务器端打印a connect have come,然后停止在了readLine()这里,而客户端打印了stay!!!也停在了readLine() 这里,然后就发生了阻塞,可是客户端竟然打印了stay!!!说明,已经像输出流写入了数据了阿,怎么服务器端会阻塞在readLine,实在不清楚,请大家帮忙看下,指点下,谢谢了


------解决方案--------------------
嘿嘿,我找到原因了。 

分析如下:
readLine为什么会阻塞呢??readLine是读一行,那它怎么判断是不是一行呢?也就是说,他读到什么地方才停止呢?明显是要读到/r/n的回车换行符,它才会认为这个是完整的一行,而你输入的str中并没有回车和换行,所以阻塞了.

把String str="hello !I 'm coming!!"; 
改为: String str="hello !I 'm coming!!\r\n"; 
则可以正常运行.
散分~
------解决方案--------------------
呵呵

lz不错啊

对了
我就在这里问一个问题了

换行的时候为什么要\r\n啊

一个是换行
一个是回车
真的有点搞不懂