我的程序如下,不能进行socket连接,但如果我吧BufferedReader类换成DataInputStream的话就没问题,怎么会这样?
public void sendxml(String xml){
Socket socket;
String len;
InputStream Is;
OutputStream Os;
BufferedReader DIS;
PrintStream  PS;
try{
//向主机名为args[0]的服务器申请连接
//注意端口号要与服务器保持一致:1001
socket=new Socket("10.21.5.19",1001);
System.out.println("client ok");
System.out.println("************************************************");
System.out.println("");
//获得对应socket的输入/输出流
Is=socket.getInputStream();
Os=socket.getOutputStream();
//建立数据流
 DIS= new BufferedReader(new InputStreamReader(Is));
PS = new PrintStream(Os);
System.out.print("you say:"+xml);
PS.print(xml); //将读取得字符串传给server
System.out.println("");
System.out.println("please wait server`s message...");
System.out.println("");backxml=DIS.readLine(); //从服务器获得字符串 
System.out.println("server said:"+backxml); //打印字符串//关闭连接
DIS.close(); //关闭数据输入流
PS.close(); //关闭数据输出流
Is.close(); //关闭输入流
Os.close(); //关闭输出流
socket.close(); //关闭socket 
}
catch(Exception e){
System.out.println("连接Error:"+e);
}
}

解决方案 »

  1.   

    faint
    BufferedReader是用来读取文本文件流的,
    仔细看看它的api文档阿
    Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes. In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,  BufferedReader in
       = new BufferedReader(new FileReader("foo.in"));
      will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient. Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.
      

  2.   

    比如你要发送String str = "测试";字段,如果你能保证发送前字符编码是正确的,不会乱码,那么接收到的自然就是正确的了。
    如果发送前就为乱码
    可以先转一下:(类似以下处理)
    str=new String (str.getBytes("ISO-8859-1"),"gb2312");
    其实如果只是发送简单的中文字串,直接使用print或者readLine方法发送和接收倒也不会有什么大问题,但要顾及到很多细节的化,最好打包成byte[]数组发送为好,接收到再转为String
    使用DateInputStream和DateOutputStream的write方法和read方法发送和接收
    当然打包解包又会复杂一些