WEB开发网
开发学院WEB开发Jsp 利用Socket进行Java网络编程(三) 阅读

利用Socket进行Java网络编程(三)

 2008-01-05 19:25:01 来源:WEB开发网   
核心提示:作者: 郗旻 附:服务器的实现代码import java.net.*;import java.io.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class talkServer{ public stati

  作者: 郗旻
  附:服务器的实现代码
  import java.net.*;
  import java.io.*;
  import java.awt.event.ActionEvent;
  import java.awt.event.ActionListener;
  public class talkServer
  { public static void main(String[] args)
   { try
    { file://建立服务器
     ServerSocket server = new ServerSocket(9998);
     int i=1;
     for(;;)
      { Socket incoming = server.accept()
       new ServerThread(incoming,i).start();
       i++;
      }
     }catch (IOException ex){
     ex.PRintStackTrace();
    }
   }
  }
  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 s,int c)
   { threadNum = c;
    socket = s;
   }
  public void actionPerformed(ActionEvent e)
  { Object source = e.getSource();
   try{
    if(source==t.BTnSend)
     { out.println(t.getTalk());
      t.clearTalk();
    }else
    if(source==t.btnEnd)
     { out.println("谈话过程被对方终止");
      out.close();
      in.close();
      talking = false;
     }
   }catch(IOException ex){
   }
  }
  public void run()
  { try{
    t=new talkServerFrm(new Integer(threadNum).toString(),this);
    t.setSize(500,500);
    t.show();
    in = new BufferedReader(new
        InputStreamReader(socket.getInputStream()));
    out = new PrintWriter(socket.getOutputStream(),true);
   }catch(Exception e){
  }
   new Thread()
   { public void run()
    { try{
      while(true)
      { checkInput();
       sleep(1000);
    }
   }catch (InterruptedException ex){
   }catch(IOException ex){
   }
   }
   }.start();
   while(talking)
   { }
   t.dispose();
   }
  private void checkInput() throws IOException
  { String line;
   if((line=in.readLine())!=null)
    t.setPartner(line); file://这是界面类里的方法,
    file://用来将line的内容输出到用户界面
   }
  }

Tags:利用 Socket 进行

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接