熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

利用Socket進行Java網絡編程(三)

2022-06-13   來源: Java核心技術 

  作者 郗旻
  附服務器的實現代碼
  import *;
  import javaio*;
  import javaawteventActionEvent;
  import javaawteventActionListener;
  public class talkServer
  { public static void main(String[] args)
   { try
    { file://建立服務器
     ServerSocket server = new ServerSocket();
     int i=;
     for(;;)
      { Socket incoming = serveraccept()
       new ServerThread(incomingi)start();
       i++;
      }
     }catch (IOException ex){
     exprintStackTrace();
    }
   }
  }
  class ServerThread extends Thread implements ActionListener
  {
   private int threadNum;
   private Socket socket;
   talkServerFrm t;
   BufferedReader in;
   PrintWriter out;
   private boolean talking=true;
   public ServerThread(Socket sint c)
   { threadNum = c;
    socket = s;
   }
  public void actionPerformed(ActionEvent e)
  { Object source = egetSource();
   try{
    if(source==tbtnSend)
     { outprintln(tgetTalk());
      tclearTalk();
    }else
    if(source==tbtnEnd)
     { outprintln(談話過程被對方終止);
      outclose();
      inclose();
      talking = false;
     }
   }catch(IOException ex){
   }
  }
  public void run()
  { try{
    t=new talkServerFrm(new Integer(threadNum)toString()this);
    tsetSize();
    tshow();
    in = new BufferedReader(new
        InputStreamReader(socketgetInputStream()));
    out = new PrintWriter(socketgetOutputStream()true);
   }catch(Exception e){
  }
   new Thread()
   { public void run()
    { try{
      while(true)
      { checkInput();
       sleep();
    }
   }catch (InterruptedException ex){
   }catch(IOException ex){
   }
   }
   }start();
   while(talking)
   { }
   tdispose();
   }
  private void checkInput() throws IOException
  { String line;
   if((line=inreadLine())!=null)
    tsetPartner(line); file://這是界面類裡的方法
    file://用來將line的內容輸出到用戶界面
   }
  }
  
  
  

From:http://tw.wingwit.com/Article/program/Java/hx/201311/25829.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.