点击这里给我发消息 点击这里给我发消息

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

添加时间:2013-12-7
    相关阅读: 网络

  作者: 郗旻
  附:服务器的实现代码
  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的内容输出到用户界面
   }
  }
  
  
  
 
咨询热线:020-85648757 85648755 85648616 0755-27912581 客服:020-85648756 0755-27912581 业务传真:020-32579052
广州市网景网络科技有限公司 Copyright◎2003-2008 Veelink.com. All Rights Reserved.
广州商务地址:广东省广州市黄埔大道中203号(海景园区)海景花园C栋501室
= 深圳商务地址:深圳市宝源路华丰宝源大厦606
研发中心:广东广州市天河软件园海景园区 粤ICP备05103322号 工商注册