本人求购聊天室程序,给了,立刻给分

解决方案 »

  1.   

    import java.applet.*;
    import java.net.*;
    import java.io.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class MultiTalk extends Frame implements ActionListener, Runnable {    static final long serialVersionUID = -2996362037788334400L;    static final short APP_STATUS_FINISHED = 0;
        static final short APP_STATUS_TALKING  = 1;
        static final short APP_STATUS_LISTENER = 2;
        static final String APP_TITLE = new String("P2P TALKING");
        static final String HOST_IP   = new String("127.0.0.1");
        static final short nPortNum   = 5000;
        String strConnectIP  = HOST_IP;
        short nConnectPort   = nPortNum;
        short nCurrentStatus = 0;
        static final short MAX_CLIENT_NUM = 50;
        private short nClientNum     = 0;    Thread mainThread;
        TalkThread[] tThread;
        ServerSocket server;
        Socket[] client;
        Socket client1;
        InputStream in;
        OutputStream out;    MenuBar mbar;
        Menu menu1,menu2;
        MenuItem mitem1S,mitem1C,mitem1X,mitem2H;
        Label label;
        TextField tf;
        Button btn;
        TextArea ta;    public MultiTalk() {      super(APP_TITLE);
          setSize(350,490);
          setLocation(100,80);
          setLayout(null);
          label = new Label("Talking:");
          tf  = new TextField(20);
          btn = new Button("确定");
          ta  = new TextArea();
          mbar  = new MenuBar();
          menu1 = new Menu("操作");
          menu2 = new Menu("帮助");
          mitem1S = new MenuItem("开始监听");
          mitem1C = new MenuItem("连接");
          mitem1X = new MenuItem("退出");
          mitem2H = new MenuItem("关于");      menu1.add(mitem1S);
          menu1.add(mitem1C);
          menu1.addSeparator();
          menu1.add(mitem1X);
          menu2.add(mitem2H);
          mbar.add(menu1);
          mbar.add(menu2);
          setMenuBar(mbar);      add(label);
          add(tf);
          add(btn);
          add(ta);
          label.setBounds(10,50,50,20);
          tf.setBounds(70,50,230,20);
          btn.setBounds(300,50,40,20);
          ta.setBounds(10,75,330,400);      mitem1S.addActionListener(this);
          mitem1C.addActionListener(this);
          mitem1X.addActionListener(this);
          mitem2H.addActionListener(this);
          tf.addActionListener(this);
          btn.addActionListener(this);
    ///**
          addWindowListener(new WindowAdapter(){
              public void windowClosing(WindowEvent e) {
                System.exit(0);
              }
          });
    // */      setVisible(true);
        }
        public void actionPerformed(ActionEvent e) {      if(e.getSource()==mitem1S) {
              startListener(true);      } else if(e.getSource()==mitem1C) {
              startTalking();      } else if(e.getSource()==mitem1X) {
              startListener(false);      } else if(e.getSource()==mitem2H) {
              //
          } else {
              //Send Message!
              if(nCurrentStatus==APP_STATUS_LISTENER) {            short nCount=0;
                String str = tf.getText();
                byte[] data = str.getBytes();
                tf.setText(null);
                ta.append("服务器发标:"+str+"\n");            for(short i=0; i<MAX_CLIENT_NUM; i++) {
                    //对于这里来说。其实i只要到nClientNum就够了。
                    if(client[i]!=null) {
                      if(!client[i].isConnected()) {
                          stopTalkThreadi(i);
                          continue;
                      }
                      ta.append("          给  "+client[i].getInetAddress()+":Thread("+i+")\n");
                      try {
                          client[i].getOutputStream().write(data);
                      } catch(IOException ioe) {}
                      nCount++;
                    }
                }
                ta.append("\n");
                if(nCount==0)
                    ta.append("没有任何用户连接,信息空发;\n");
              }
              else if(nCurrentStatus==APP_STATUS_TALKING) {
                String str = tf.getText();
                byte[] data = str.getBytes();
                tf.setText(null);
                ta.append("我说:"+str+"\n");
                try {
                    out.write(data);
                } catch(NullPointerException ioe) {
                    ta.append("当前无可用连接;信息发送失败;\n");
                } catch(IOException ioe) {}
              }
              else {
                ta.append("未做服务或非客户端\n");
              }
          }
        }
      

  2.   


        public void startListener(boolean status) {      if( (status)&&(mainThread==null) ) {          nCurrentStatus = APP_STATUS_LISTENER;
              mitem1S.setLabel("取消监听");
              try {
                server  = new ServerSocket(nPortNum);
                //固定的监听端口
              } catch(IOException e) {
                mitem1S.setLabel("开始监听");
                ta.append("建立连接失败:\n=====\n"+e+"\n");
                stopTalk1();
                return;
              }
              ta.append("初始化主线程.....\n");
              mainThread = new Thread(this,"ConnectListener");
              mainThread.setPriority(7);
              mainThread.start();
              client  = new Socket[MAX_CLIENT_NUM];
              tThread = new TalkThread[MAX_CLIENT_NUM];      }
          else {          if(nCurrentStatus==APP_STATUS_LISTENER) {
                //mainThread.stop();//结束监听;
                mitem1S.setLabel("开始监听");
                ta.append("关闭对"+nConnectPort+"端口的监听,退出成功!\n");
              }
              else if(nCurrentStatus==APP_STATUS_TALKING) {
                ta.append("退出成功!\n");
              }
              else {
                ta.append("没有可用连接,不用退的!\n");
              }
              stopTalk1();
          }
        }    public void startTalking() {      if(mainThread==null) {
               nCurrentStatus = APP_STATUS_TALKING;
               mainThread = new Thread(this,"TalkingThread");
               mainThread.setPriority(5);
               mainThread.start();
          }
          else{
              ta.append("已经处于连接状态;\n");
          }
        }    public void run() {      Thread thisThread = Thread.currentThread();
          if(thisThread==mainThread) {          if(nCurrentStatus==APP_STATUS_LISTENER) {
                if(server==null) {
                //  thisThread.stop();
                    return;
                }
                if(nClientNum>=MAX_CLIENT_NUM) {
                    ta.append("客户端连接数量达到饱和,监听结束;\n");
                //  thisThread.stop();
                    return;
                }
                while(thisThread==mainThread) {
                    try {
                      ta.append("对"+nConnectPort+"端口做监听(线"+nClientNum+")....\n");
                      client[nClientNum]  = server.accept();
                      tThread[nClientNum] = (new TalkThread(client[nClientNum])).go();
                    } catch(IOException ioe) {
                    } catch(NullPointerException ioe) {
                      stopTalk1();
                      return;
                    }
                }
              }
              else if(nCurrentStatus==APP_STATUS_TALKING) {
                OpenDialog myDialog = new OpenDialog(this,"连接到:");
                myDialog.setVisible(true);
                if(!myDialog.getStatus()) {
                    stopTalk1();
                    return;
                }
                try {
                    client1 = new Socket(strConnectIP,nConnectPort);
                    in  = client1.getInputStream();
                    out = client1.getOutputStream();
                    ta.append("已与服务器"+client1.getInetAddress()+"成功建立通讯;\n========================\n");
                } catch(IOException ioe) {
                    ta.append("建立失败:"+ioe.getMessage()+"\n");
                    stopTalk1();
                }
                while(true) {
                // Receive Message!
                    try{
                      byte[] buf = new byte[40];
                      in.read(buf);
                      if(isDisconnect(buf[0])) {
                          ta.append("与服务器断开连接!\n");
                          stopTalk1();
                          return;
                      }
                      ta.append("服务器:" + new String(buf));
                      ta.append("\n");
                      Thread.sleep(500);
                    } catch (IOException e) {
                      ta.append("遗失对服务器的连接Exception1\n");
                      stopTalk1();
                      return;
                    } catch (InterruptedException e) {
                      ta.append("遗失对服务器的连接Exception2\n");
                      stopTalk1();
                      return;
                    }
                }
              }
              else {
                ta.append("没有任何可用连接\n");
              }      }
          //thread finished;
        }
      

  3.   


        boolean isDisconnect(byte bit) {
          if(bit==0) {
              return true;
          }
          return false;
        }    void stopTalk1() {
          nCurrentStatus = APP_STATUS_FINISHED;
          stopTalk();
        }
        void stopTalk() {      if(mainThread!=null){
          //  mainThread.stop();//这里为什么不能用 stop();
              mainThread = null;
          }      if(server!=null) {
              try {
                server.close();
              } catch(IOException e) {}
              server = null;
          }
          if(client!=null){
              for(int i=0; i<MAX_CLIENT_NUM; i++)
                if(client[i]!=null) {
                    stopTalkIOStream(tThread[i].in,tThread[i].out);
                    stopTalkThread(client[i]);
                    client[i]  = null;
                    tThread[i] = null;
                }
              client  = null;
              tThread = null;
          }
          stopTalkIOStream(in,out);
          if(client1!=null){
              stopTalkThread(client1);
          }      System.gc();
        }
        void stopTalkThreadi(int iThread) {
          stopTalkIOStream(tThread[iThread].in,tThread[iThread].out);
          stopTalkThread(client[iThread]);
          client[iThread]  = null;
          tThread[iThread] = null;
        }
        void stopTalkThread(Socket socket) {
          if(socket!=null) {
              try {
                socket.close();
              } catch(IOException e) {}
              socket = null;
          }
        }
        void stopTalkIOStream(InputStream in, OutputStream out) {
          if(in!=null) {
              try {
                in.close();
              } catch(IOException e) {}
              in = null;
          }
          if(out!=null) {
              try {
                out.close();
              } catch(IOException e) {}
              out = null;
          }
        }
        public static void main(String[] args) {
          new MultiTalk();
        }    class TalkThread extends Thread {      static final long serialVersionUID = -2996362030133559274L;      private final short thisID = nClientNum++;
          InputStream in;
          OutputStream out;      public TalkThread(Socket socket) {          super("TalkThread"+String.valueOf(nClientNum));
              ta.append("Thread("+String.valueOf(thisID)+")已与客户端("+socket.getInetAddress()+")["+thisID+"]成功建立通讯;\n=================================\n");
              try {
                in  = socket.getInputStream();
                out = socket.getOutputStream();
              } catch(IOException e) {}
          }
          public short getThreadID() {
              return thisID;
          }      public TalkThread go() {
              start();
              return this;
          }      public void run() {          while(client[thisID]!=null) {
                try {                if(!client[thisID].isConnected()) {
                      stopTalkThreadi(thisID);//断开连接;
                      return;
                    }                byte[] data = new byte[40];
                    in.read(data);
                    if(isDisconnect(data[0])) {
                      ta.append("客户端"+client[thisID].getInetAddress()+"("+thisID+")已断开连接!\n");
                      stopTalkThreadi(thisID);
                      return;
                    }
                    ta.append(client[thisID].getInetAddress()+"("+thisID+")说:"+(new String(data)));
                    ta.append("\n");
                    Thread.sleep(1000);
                } catch(IOException e) {
                    try {
                      ta.append("与"+client[thisID].getInetAddress()+"("+thisID+")遗失连接exception1!\n");
                      stopTalkThreadi(thisID);
                    } catch(NullPointerException ioe) {}
                    return;
                } catch(InterruptedException e) {
                    ta.append("与"+client[thisID].getInetAddress()+"("+thisID+")遗失连接exception2!\n");
                    stopTalkThreadi(thisID);
                    return;
                }
              }
          }
        }//END TalkThread Class    class OpenDialog extends Dialog implements ActionListener {      static final long serialVersionUID = -2199636203015991542L;      TextField tfPort = new TextField(String.valueOf(nConnectPort));
          TextField tfIp   = new TextField(strConnectIP);
          Button btOk      = new Button("确定");
          Button btCancel  = new Button("取消");      private boolean bBT_OK_CLICKED = false;      public OpenDialog(Frame parent, String title) {
              super(parent, title, true);          Label lbPort = new Label("端口号:");
              Label lbIp   = new Label("IP地址:");
              setLayout(null);
              setSize(220,120);
              setLocation(250,300);          add(lbPort);
              add(lbIp);
              add(tfPort);
              add(tfIp);
              add(btOk);
              add(btCancel);          lbPort.setBounds(10,35,40,20);
              lbIp.setBounds(10,55,40,20);
              tfPort.setBounds(60,35,140,20);
              tfIp.setBounds(60,55,140,20);
              btOk.setBounds(50,85,40,20);
              btCancel.setBounds(150,85,40,20);          tfPort.addActionListener(this);
              tfIp.addActionListener(this);
              btOk.addActionListener(this);
              btCancel.addActionListener(this);
              addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    dispose();
                   //hidden this dialog
                }
              });
          }      public boolean getStatus() {
              return bBT_OK_CLICKED;
          }      public void actionPerformed(ActionEvent e) {          if(e.getSource()!=btCancel) {
                strConnectIP = tfIp.getText();
                try {
                    nConnectPort = (short)Integer.parseInt(tfPort.getText());
                } catch (Exception ioe) {
                    nConnectPort = nPortNum;
                    ta.append("未设置成功;采用默认的"+nPortNum+"\n");
                }
                bBT_OK_CLICKED = true;
              }
              dispose();
          }    }}
      

  4.   

    谢谢大家了,我几天没有来上CSDN了,今天刚来,我把分给分了,呵呵,不好意思啊,各位~~
      

  5.   

    问你一下,你写的 程序,能在自己的电脑上运行吗,你的ociq是多少啊,可以告诉我吗,我想找写学JAVA的高手,望赐教
      

  6.   

    请把 聊天室的程序发到我的E-mail好吗,谢谢了,
    我的E-mail是:[email protected]
    谢谢了啊。大哥。小弟拜求。
      

  7.   

    我学java才两个月.呵呵。
    也是菜鸟.源代码全都在这里了呀。~~
      

  8.   

    可以的.你那里不能执行么?
    我用的是JDK1.5的
    在java.sun.com里下的 NetBeans4.0
      

  9.   

    我这边也可以执行,不过只室单线程得。我所要得室多线程得啊。大哥。我得oicq是43342651,有时间你加我吧。大家可以一起学JAVA.呵呵
    好了,谢谢大哥