电脑技术学习

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

dn001
内容: 出自:天极网 郗旻 2002年11月11日 09:28
附:服务器的实现代码

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的内容输出到用户界面
 }
}

Java, java, J2SE, j2se, J2EE, j2ee, J2ME, j2me, ejb, ejb3, JBOSS, jboss, spring, hibernate, jdo, struts, webwork, ajax, AJAX, mysql, MySQL, Oracle, Weblogic, Websphere, scjp, scjd

标签: 编程