我这几天在看孙鑫讲题的一个服务器和客户端发信息的一个课程!里面有一个程序是这样的:
class Server extends Thread{
 private Socket s;
 public Server(Socket s){
   this.s=s;//1.他这样表试的意思是什么?
  }
  public void run(){
   //2.这里是Thread的默认方法,可是为什么要用呢.我却不是很明白
    try{
      OutputStream ou = s.getOutputStream();
      InputStream in = s.getInputStream();
      ou.write("用户你好".getBytes());
      byte[] b = new byte[100];
      in.read(b);
      System.out.println(new String(b, 0, b.length));
      s.close();
      ou.close();
      in.close();
    }catch(Exception ce){
      ce.printStackTrace();
    }
  }
  public static void main(String[] args) {
    if (args.length > 0)
      serve();
    else
      client();
  }  public static void serve() {
    try {
      ServerSocket ss = new ServerSocket(5000);
      while(true){
        Socket s=ss.accept();
        new Server(s).start();//3.还有这里的声明
      }
    }catch (Exception ce) {
      ce.printStackTrace();
    }
  }上面三个问题,真是把我搞晕了.我看了一天的Thread讲解,可是孙鑫讲得很死板,我理解起来困难!
希望有高手指点!

解决方案 »

  1.   

    1    this.s=s;表示把方法形参的Socket类型的s赋值给该类的Socket类型的s,由于变量名相同,所以类里的s用this修饰下。
    2    Thread的run方法表示运行该线程的时候调用该run方法
    3    new Server(s).start(),前部分new Server(s)表示new了一个对象,然后调用该对象的start方法。start方法就是执行线程,即执行线程里的run代码段!
      

  2.   

    应该先看erve()方法
    在主函数中 如果有参数的话就调用erve()方法
    新建一个服务器socket把这个socket传给Server的一个实例 就是new Server(s)
    这个socket的引用就给了 this.s 在run方法中使用这个socket
    这个Server继承了Thread 类
    当然就要重写run方法