看ing,不过也太长了点吧,累眼~~~

解决方案 »

  1.   

    第二次发送时,socket已经关闭,抛出了异常,但是你的异常捕获什么都不作,所以建议今后在异常捕获里加上一句:
    e.printStackTrace()
    方便错误定位。
      

  2.   

    说一下server传给client时,你用vector的作用
      

  3.   

    不用vector怎么确定显示的始终是最新的消息呢?不好意思,我真的是菜鸟,说的不对,不要笑话我
      

  4.   

    我做的一个聊天室,有些功能没实现,只有简单的聊天功能,看看,可以探讨探讨。
    服务端代码:
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.awt.*;public class ClientPoint extends JFrame{
      static int SERVERPORT=8088;
      static String SERVERADDRESS="10.215.215.108";
      private BufferedReader cin=null;
      private PrintWriter cout=null;
      private Socket client=null;
       public String clientname;
      private JPanel jPanel1=new JPanel();
      private JTextField jTextSendInfo=new JTextField(38);
      private JTextArea jTextGetInfo=new JTextArea(16,33);  
      public JScrollPane areaScrollPane=new JScrollPane(jTextGetInfo);  
      private Button Send=new Button("发送");
      private Button Link=new Button("连接");
      
      public ClientPoint(){  
        super("阿杰哥聊天室^_^");    
       enableEvents(AWTEvent.WINDOW_EVENT_MASK);    
        setSize(480,465);
        jPanel1.add("South",jTextSendInfo);
        jPanel1.setBackground(new Color(75, 234, 166));
    jTextGetInfo.setBackground(new Color(122,150,223));
        jTextGetInfo.setFont(new java.awt.Font("Dialog", 0, 15));
        jTextGetInfo.setForeground(new Color(176, 42, 0));
        this.setResizable(false);
        Send.setBackground(Color.pink);
        Send.setForeground(Color.blue);
        Send.setBounds(new Rectangle(92, 400, 90, 37));
        Link.setBackground(Color.pink);
        Link.setForeground(Color.blue);   
        areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        areaScrollPane.setAutoscrolls(true);
       jTextSendInfo.setText("");
        jPanel1.add("North",areaScrollPane);
        jTextGetInfo.setEditable(false);
        jPanel1.add("South",Send);
        Send.setEnabled(false);
        jPanel1.add("South",Link);
        Send.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){
               if(!jTextSendInfo.getText().equals("")){
               cout.println("["+clientname+"]:"+jTextSendInfo.getText());
               cout.flush();          
               jTextSendInfo.setText("");
              jTextSendInfo.setFocusable(true);          
                }
                else JOptionPane.showMessageDialog(null,"阿杰哥警告:消息不能为空!!","消息对话框",JOptionPane.WARNING_MESSAGE);
                }});
        Link.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){
               if(!jTextSendInfo.getText().equals("")){
                  clientname=jTextSendInfo.getText();
                  connect();             
                  Link.setEnabled(false);
                  Send.setEnabled(true);
                  jTextSendInfo.setText("");
              }
              else JOptionPane.showMessageDialog(null,"阿杰哥警告:用户名不能为空!!","消息对话框",JOptionPane.WARNING_MESSAGE);
              }});
        this.setContentPane(jPanel1);
      }
      public void connect(){
        try{
          client=new Socket(SERVERADDRESS,SERVERPORT);       
           cout=new PrintWriter(client.getOutputStream());          
             cin=new BufferedReader(
              new InputStreamReader(client.getInputStream()));
              cout.println("欢迎["+clientname+"]进入 阿杰哥聊天室");
              cout.flush();
               Receiver r=new Receiver();
              r.start();    
      }catch(Exception e){
             
         e.printStackTrace();
      }
    }
    protected void processWindowEvent(WindowEvent e){
         if(e.getID()==WindowEvent.WINDOW_CLOSING){
             quit();
         }
         super.processWindowEvent(e);
        }
        public static void main(String[] args){
          ClientPoint cp=new ClientPoint();
          cp.show();
          
        }class Receiver extends Thread{
    public void run(){
    String msg=null;
    JScrollBar sb;
    try{
    msg=cin.readLine();
    while(true){
    jTextGetInfo.append(msg+"\n");
    sb=areaScrollPane.getVerticalScrollBar();
    sb.setValue(sb.getMaximum()+50);
    jTextSendInfo.setEnabled(true);
    msg=cin.readLine();
    }
    }catch(Exception e){
    Send.setEnabled(false);
    }
    }
    }
    void quit(){
    try{
    cout.println("["+clientname+"]离开 阿杰哥聊天室");
    cout.flush();
    cout.println("exit");
    cout.flush();
    System.out.print("lianjieduankai");
    cin.close();
    cout.close();
    client.close();
    }catch(Exception e){}
    finally{System.exit(0);
    }
    }
    }客户端代码:import java.net.*;
    import java.io.*;public class ServerPoint extends Thread{
      static int SERVERPORT=8088;
      private Socket client;
      public static int i=0;
      public static String[] vct=new String[10];  
      public ServerPoint(){}
      public void run(){
        ClientThread.log("服务器端程序启动");
        try{
         ServerSocket server=new ServerSocket(SERVERPORT);
         while(true){     
            client=server.accept();        
            ClientThread ct=new ClientThread(client);
           ct.start();
         }
       }catch(Exception e){
         e.printStackTrace();
         ClientThread.log("服务器端程序关闭");
         System.exit(0);
       }
      }
      public static void main(String[] args){
      
        ServerPoint sp=new ServerPoint();
        sp.start();
      }
      public static synchronized void message(String msg){
        vct[i]=msg;
       i=(i+1)%10;
       vct[i]="*";
      
       }
    }
    class ClientThread extends Thread{  
    private static int ii=0;
      private Socket s;
      String msg=null;
      ServerSocket serverSocket=null;
      Socket socket=null;
      BufferedReader cin=null;
      PrintWriter cout=null;  
      public ClientThread(Socket s){    
        this.s=s;   
      }
      public void run(){
        try{    
           cin=new BufferedReader(
              new InputStreamReader(s.getInputStream()));
             
          cout=new PrintWriter(s.getOutputStream());
          SendToAll sta=new SendToAll();
          sta.start();        
          msg=cin.readLine();
          ii++;
          System.out.println("some connect us!聊天室里总共有"+ii+"个人");
          while(!msg.equals("exit")){
           ServerPoint.message(msg);
           msg=cin.readLine();
           }
          
          if(msg.equals("exit"))
          { --ii;
           System.out.print("someone exit\n聊天室里总共有"+ii+"个人");    
          cin.close();
           cout.close();
           s.close();      
          }    
        }catch(Exception e){
          e.printStackTrace();
        }
      }
      static void log(String strInfo){
        System.out.println(strInfo);
      }
    class SendToAll extends Thread{
    private int j=-1;
    public void run(){
    while(true)
    {
    try{
    sleep(500);
    if(j==-1){
    if(!ServerPoint.vct[0].equals("*")){
    cout.println(ServerPoint.vct[0]);
    cout.flush();
    j=1;
    }
    else {
    cout.println(ServerPoint.vct[1]);
    cout.flush();
    j=2;
    }
    }
    while(!ServerPoint.vct[j].equals("*"))
    {

    cout.println(ServerPoint.vct[j]);
    cout.flush();
    j=(j+1)%10;

    }
    }catch(Exception e){}
    }
    }
    }
    }
      

  5.   

    你把代码到编译器里再看嘛
    已经在QQ里加你为好友,不过我最近比较忙,不经常开QQ。
      

  6.   

    程序已经给你改好了,但由于设计问题,只能在发送消息时读取其他用户的message。如要完善该聊天程序,建议你重新设计。服务器端:
    import java.io.*;
    import java.net.*;
    import java.util.*;class Customer implements Serializable 
    {
         String message;
         
    }
    public class ServerApp extends Thread
    {
         ServerSocket server;
    Vector temp;     public ServerApp()
          { 
            temp = new Vector();
    try{
                server =new ServerSocket(1001);
             }
             catch(IOException e)
             {
                  fail(e,"Could not start Server!");
                  
             }
             System.out.println("Server started...");
             this.start();
          }
          
          public void fail(Exception ee,String str)
          {
              System.out.println(str+"."+ee);
          }
          public void run()
          {
               try{
                       while(true)
                       {
                          Socket client=server.accept();
                          Concet con=new Concet(client,this.temp);
                          
                       }
                  }
                catch(IOException e)
                {
                     fail(e,"Not Listening");
                }  
          }
          public static void main(String args[])
          {
              new ServerApp();
          }
          
    }
    class Concet
    {
       protected Socket netClient;
       protected ObjectInputStream fromClient;
       protected PrintStream toClient;
    Vector message;   Customer cut;
       
       public Concet(Socket cli,Vector s)
       {
           netClient=cli;
    message = s;       try{
                     fromClient=new ObjectInputStream(netClient.getInputStream());
                     toClient=new PrintStream(netClient.getOutputStream());
              }
            catch(IOException e)
            {
               try{
                        netClient.close();
                  }
               catch(IOException e1)
               {
                     System.out.println("Unable to setup Stream"+e);
                     return;
               }
            }  
             Object obj;
             try{
                      obj=fromClient.readObject();
                
                      if(obj instanceof Customer)
                      System.out.println(obj.toString());
                      cut=(Customer)obj;
    message.add(cut.message);
    Enumeration enum = message.elements();
    while(enum.hasMoreElements())
    {
              toClient.println(enum.nextElement());
    }

              }
              catch(ClassNotFoundException e1)
              {
                    System.out.println("Error in reading object"+e1);
              }
              catch(IOException e)
                {
                      System.out.println("IO Error"+e);
                }
                finally
                {
                   try{
                        netClient.close();
                      }
                   catch(IOException e)
                   {
                       System.out.println("Close error"+e);
                   }
                }

                  
        }
    }
      

  7.   


    客户端:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.*;class Customer  extends Object implements Serializable
    {
         String message;
    }
    public class chatFrame extends JFrame 
    {
      Socket toServer;       
      BufferedReader fromServer;
      ObjectOutputStream streamToServer;
      /*ÒÔ϶¨ÒåUI±äÁ¿*/
      JPanel jPanel1 = new JPanel();
      JLabel lblMessage = new JLabel();
      JLabel lblUser = new JLabel();
      JScrollPane scrMessage = new JScrollPane();
      JScrollPane scrUser = new JScrollPane();
      JTextArea txtMessage = new JTextArea();
      JTextArea txtUser = new JTextArea();
      JTextField txtUserMessage = new JTextField();
      JButton butSend = new JButton();
      JButton butLogout = new JButton();
      GridBagLayout gridBagLayout1 = new GridBagLayout();  public chatFrame() 
      {
        try 
        {
          jbInit();
        }
        catch(Exception e) 
        {
          e.printStackTrace();
        }
      }
      
      
      private void jbInit() throws Exception 
      {
        //toServer=new Socket("127.0.0.1",1001);   
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setTitle("Chat Room");
        
        jPanel1.setLayout(gridBagLayout1);
        lblMessage.setText("Chat Message");
        lblUser.setAlignmentY((float) 0.5);
        lblUser.setText("Users Online");
        txtMessage.setText("");
        txtUser.setText("");
        txtUserMessage.setText("");
        butSend.setText("Send");
        buttonClick opp=new buttonClick();
        butSend.addActionListener(opp);
        butLogout.setFont(new java.awt.Font("Dialog", 1, 11));
        butLogout.setForeground(Color.red);
        butLogout.setText("Logout");
        this.getContentPane().add(jPanel1, BorderLayout.CENTER);
        jPanel1.add(lblMessage,  new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
                ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(41, 37, 0, 0), 13, 6));
        jPanel1.add(lblUser,  new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0
                ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(12, 25, 0, 29), 22, 3));
        jPanel1.add(scrMessage,  new GridBagConstraints(0, 1, 2, 2, 1.0, 1.0
                ,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(23, 37, 0, 0), 188, 229));
        scrMessage.getViewport().add(txtMessage, null);
        jPanel1.add(scrUser,  new GridBagConstraints(2, 2, 1, 1, 1.0, 1.0
                ,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(16, 26, 0, 56), 52, 205));
        scrUser.getViewport().add(txtUser, null);
        jPanel1.add(butSend,  new GridBagConstraints(1, 4, 1, 1, 0.0, 0.0
                ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(12, 43, 15, 0), 9, -5));
        jPanel1.add(butLogout,  new GridBagConstraints(2, 4, 1, 1, 0.0, 0.0
                ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(9, 44, 15, 23), 0, 1));
        jPanel1.add(txtUserMessage,  new GridBagConstraints(0, 3, 2, 1, 1.0, 0.0
                ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(14, 37, 0, 0), 188, 1));
        this.setSize(500,570);
        this.setVisible(true);
      
      }
      
      
      class buttonClick implements ActionListener
        {
        
            public void actionPerformed(ActionEvent e)
            {
                  
      Object obj=e.getSource();
                  if (obj==butSend)
                  {
    Customer data=new Customer();
                        data.message=txtUserMessage.getText();
                        try
                        {
                            
    toServer=new Socket("127.0.0.1",1001);   
    streamToServer=new ObjectOutputStream(toServer.getOutputStream());                        streamToServer.writeObject(data); fromServer=new BufferedReader(new InputStreamReader(toServer.getInputStream()));                        String str=fromServer.readLine();
    Vector ve=new Vector();
    txtMessage.setText("");
    while(str!=null)
    {

    System.out.println(str);
                            ve.addElement(str);
    str = fromServer.readLine();
    }
    for(int i=0;i<ve.size();i++)
                            {
                                String mess=(String)ve.elementAt(i);
                                txtMessage.append(mess);
                                txtMessage.append("\n");
                                
                                
                            }  
                            
                          streamToServer.close();
                          fromServer.close();
    txtUserMessage.setText("");
                       }
                        catch(InvalidClassException e1)
                        { e1.printStackTrace();}
                        catch(NotSerializableException e2)
                        {e2.printStackTrace();}
                        catch(Exception e3)
                        {e3.printStackTrace();}
                  }
            }
        }
      
      public static void main(String args[])
      {
          new chatFrame();
      }
    }