/*
运行服务端c:\java Lesson param
运行客户端eg: c:\java Lesson bos.write("Send From Server".getBytes());//这样可以bos.write(str.getBytes());//这样不可以,无内容
请问这是怎么回事啊
*/import java.net.*;
import java.io.*;
public class Lesson extends Thread
{
 private Socket s;
  public Lesson(Socket s)
  {
    this.s=s;
  }
  public void run()
  {
    try {
      OutputStream os=s.getOutputStream();
      BufferedOutputStream bos=new BufferedOutputStream(os);
      InputStream is=s.getInputStream();
     
      bos.write("Send From Server".getBytes());//这样可以
      bos.flush();      byte[] buf=new byte[100];
      int len=is.read(buf);
      String str =new String(buf,0,len);
      System.out.println(str);
 
//bos.write(str.getBytes());//这样不可以,无内容
     //bos.flush();    
     os.close();
     bos.close();
      is.close();
      s.close();
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  public static void main(String[] args)
  {
    if(args.length>0)
      server();
    else
      client();
  }
  public static void server()
  {
    try {
      ServerSocket ss=new ServerSocket(6000);
      while(true)
      {
        Socket s = ss.accept();
        new Lesson(s).start();
      }
      //ss.close();
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  public static void client()
  {
    try {
      Socket s=new Socket(InetAddress.getByName(null),6000);
      OutputStream os=s.getOutputStream();
      InputStream is=s.getInputStream();
      byte[] buf=new byte[100];
      int len=is.read(buf);
      System.out.println(new String(buf,0,len));
      os.write("Come From Client".getBytes());
      os.close();;
      is.close();
      s.close();
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }  }
}

解决方案 »

  1.   

    try {
          OutputStream os=s.getOutputStream();
          BufferedOutputStream bos=new BufferedOutputStream(os);
          InputStream is=s.getInputStream();
         
          bos.write("Send From Server".getBytes());//这样可以
          bos.flush();      byte[] buf=new byte[100];
          int len=is.read(buf);
          String str =new String(buf,0,len);
          System.out.println(str);
     
    //bos.write(str.getBytes());//这样不可以,无内容
         //bos.flush();
        
         os.close();
         bos.close();
          is.close();
          s.close();
        }//bos.write(str.getBytes());//这样不可以,无内容
         //bos.flush();
    其实这样不行是你放的地方不对,放在这里是没有效果的,因为你的服务端和客户端使用的是同一个线程,开始同时向网络信道写数据,这个没有问题,写完之后再读也没有问题,但是最后执行完写操作之后就关闭连接了,所以之后在写就收不到了另注意:最好使用8000以后的端口,服务器和客户使用不同的线程