先启动服务器端程序,再启动客户端程序。先由客户端发送一行字符串过去,服务器收到后再返回一个字符串,现在一运行程序就卡死了,求解?服务器端代码如下:public class ServerTest
{
 public static void main(String[] args) throws Exception
 {
  ServerSocket ss = new ServerSocket(4000);
  Socket socket = ss.accept();
  InputStream is = socket.getInputStream();
  String str = "";
  byte[] buffer = new byte[1024];
  int len = 0;
  while ((len = is.read(buffer, 0, buffer.length)) != -1)
  {
   str += new String(buffer, 0, len);
  }
  System.out.println("客户端发送数据为:" + str);
  
  OutputStream os = socket.getOutputStream();
  os.write("hello".getBytes());
  
  socket.close();
 }} 客户端代码为:public class ClientTest
{
 public static void main(String[] args) throws Exception
 {
  Socket socket = new Socket("127.0.0.1", 4000);
  
  OutputStream os = socket.getOutputStream();
  os.write("你好,服务器!".getBytes());
  os.flush();
  
  InputStream is = socket.getInputStream();
  int len = 0;
  byte[] buffer = new byte[1024];
  String str = "";
  while ((len = is.read(buffer, 0, buffer.length)) != -1)
  {
   str += new String(buffer, 0, len);
  }
  System.out.println("服务器发送数据为:" + str);
  
  socket.close();
 }}

解决方案 »

  1.   

    while ((len = is.read(buffer, 0, buffer.length)) != -1)这不是字符流需要一行一行的读。while换成if
      

  2.   

    如果我这边定义的字节数组比较小,而客户端发过来的数据比较大的时候,不用while肯定不能读完全啊?
    我也试过了,如果两边都是只读一次是没有问题的。我现在就是不知道为什么这么读就出问题了?
      

  3.   

    “如果我这边定义的字节数组比较小,而客户端发过来的数据比较大的时候,不用while肯定不能读完全啊?”
    双方通信的时候设定协议数据前两个字节表示数据的长度,读的时候根据读到的长度去初始化这个的byte[]数组的大小。这样就可以满足你的需求。
      

  4.   

    str += new String(buffer, 0, len);你这里读取的字节数组中不一定能转化成正确的字符串