Java网络编程之Socket(二)

  • 来源: 程序员之家 作者: sevenleaf   2010-04-07/11:34
  •       在《Java网络编程之Socket(一)》中我们已经和大家说到客户端的网络编程,下面和大家分享的是服务器的实现代码。
    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的内容输出到用户界面
    }
    }


    评论 {{userinfo.comments}}

    {{money}}

    {{question.question}}

    A {{question.A}}
    B {{question.B}}
    C {{question.C}}
    D {{question.D}}
    提交

    驱动号 更多