服务器端
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;class TestChatServer extends JFrame implements ActionListener{
  //声明变量
      Container cc;
        JTextArea jtfwest,jtfcenter,jtfbottom;
JPanel [] jpan = new JPanel[4];
JLabel [] jlabel = new JLabel[7];
JScrollPane jspw,jspc,jspb;
JButton jbufs,jbugb,jbclear;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
public TestChatServer(){   
setTitle("07Java聊天室");
    cc = this.getContentPane();  
         
  //产生面板
jpan[0] =new JPanel();
    jpan[1] = new JPanel();       
    jpan[2] = new JPanel(); //设置布局
setLayout(new BorderLayout(5,5));       
    cc.add(jpan[0],BorderLayout.WEST);
    cc.add(jpan[1],BorderLayout.CENTER);
cc.add(jpan[2],BorderLayout.SOUTH); //添加jpan[0]上的内容 
jpan[0].setLayout(new BorderLayout()); 
jtfwest = new JTextArea(20,15); 

//添加滚动条
jspw = new JScrollPane();  

//设置什么时候显示滚动条 
jspw.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);

jspw.getViewport().add(jtfwest);         
    jpan[0].add(jspw,BorderLayout.CENTER);
    
     //设置自动换行,自动换行则不会出现横向的滚动条
jtfwest.setLineWrap(true);       
    
//添加jpan[1]上的内容 
jpan[1].setLayout(new BorderLayout()); 
jtfcenter = new JTextArea(20,35);
jspc = new JScrollPane();
jspc.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); 
jspc.getViewport().add(jtfcenter);         
    jpan[1].add(jspc,BorderLayout.CENTER);
jtfcenter.setLineWrap(true);  //添加jpan[2]上的内容 
jpan[2].setLayout(new BorderLayout());
jpan[3] = new JPanel();
jlabel[0] = new JLabel("                                                                      ");
jlabel[1] = new JLabel("           ");

jbugb = new JButton("关闭");
jbugb.addActionListener(this);//注册监听器 jbclear = new JButton("清空");
jbclear.addActionListener(this); jbufs = new JButton("发送");
jbufs.addActionListener(this);
jbufs.setEnabled(false); jtfbottom = new JTextArea(5,49);
//jtfbottom.addActionListener(this);

jspb = new JScrollPane();
jspb.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); 
jspb.getViewport().add(jtfbottom);         
         jpan[2].add(jspb,BorderLayout.CENTER);
jpan[2].add(jpan[3],BorderLayout.SOUTH);
jpan[3].setLayout(new FlowLayout());

jpan[3].add(jlabel[0]);

jpan[3].add(jbufs);
jpan[3].add(jbclear);
//jpan[3].add(jlabel[1]);
jpan[3].add(jbugb);
jtfbottom.setLineWrap(true); 
      pack(); //默认容器大小与this.setSize(500,550)作用差不多
          //结束程序
          this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(330,100); //设置对话框的位置
           //设置可见
jtfbottom.requestFocus(); //获得焦点
           this.setVisible(true); 

}
//实现发送监听器
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("关闭")) //判断事件源的三种方法:3. e.getActionCommand.comparedTo("关闭")==0
{
System.exit(0);
    }

if(e.getSource()==jbufs)
{
String s=jtfbottom.getText();
sendData(s);
//jtfcenter.setText(s);    }
if(e.getSource()==jbclear){
jtfbottom.setText(null);    }
   
}
//
private void waitForConnection() throws IOException{
    jtfcenter.setText( "等待连接请求......\n" );    // allow server to accept a connection
    connection = server.accept();
         
    jtfwest.append("\n主机"+connection.getInetAddress().getHostName()+"在线\n");
} private void getStreams() throws IOException{
   // set up output stream for objects
   output=new ObjectOutputStream(connection.getOutputStream());
   output.flush();   // set up input stream for objects
   input = new ObjectInputStream(connection.getInputStream());   jtfcenter.append("\n已获得 I/O 流\n");
  }
private void processConnection() throws IOException
{
   // send connection successful message to client
   String message = "SERVER 说>>> Connection successful";
   output.writeObject(message);
   output.flush();   // enable enterField so server user can send messages
   jbufs.setEnabled(true);   // process messages sent from client
   do {      // read message and display it
      try {
         message=(String)input.readObject();
         
         jtfcenter.append("\n" + message);
         jtfcenter.setCaretPosition(jtfcenter.getText().length());
      }      // catch problems reading from client
      catch (ClassNotFoundException classNotFoundException) {
         jtfcenter.append( "\nUnknown object type received" );
      }   } while ( !message.equals("CLIENT>>> TERMINATE") );
} private void sendData(String message)
{
   // send object to client
   try {
      output.writeObject( "SERVER>>> " + message );
      output.flush();
      jtfcenter.append( "\nSERVER>>>" + message );
   }   // process problems sending object
   catch ( IOException ioException ) {
      jtfcenter.append( "\nError writing object" );
   }
}
private void closeConnection() throws IOException
{
   jtfcenter.append("\nClosing connection");
   output.close();
   input.close();
   connection.close();
}
public void runServer()
{
   // set up server to receive connections; 
   // process connections
   try {      // Step 1: Create a ServerSocket.
      server=new ServerSocket(5000, 100);      while(true){         // Step 2: Wait for a connection.
         waitForConnection();         // Step 3: Get input and output streams.
         getStreams();         // Step 4: Process connection.
         processConnection();         // Step 5: Close connection.
         closeConnection();     }
   }   // process EOFException when client closes connection 
   catch (EOFException eofException){
      System.out.println( "Client terminated connection" );
   }   // process problems with I/O
   catch (IOException ioException){
      ioException.printStackTrace();
   }
}
public static void main(String[] args){
    new TestChatServer().runServer();
        }
}

解决方案 »

  1.   

    以下是我的客户端
    客户端import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;class TestChatClient extends JFrame implements ActionListener{
      //声明变量
          Container cc;
            JTextArea jtfwest,jtfcenter,jtfbottom;
    JPanel [] jpan = new JPanel[4];
    JLabel [] jlabel = new JLabel[7];
    JScrollPane jspw,jspc,jspb;
    JButton jbufs,jbugb,jbclear;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    private String message;
    private String chatServer;
    private Socket client;
    public TestChatClient(String host){
    chatServer=host;   
    setTitle("群聊窗口");
        cc = this.getContentPane();  
             
      //产生面板
    jpan[0] =new JPanel();
        jpan[1] = new JPanel();       
        jpan[2] = new JPanel(); //设置布局
    setLayout(new BorderLayout(5,5));       
        cc.add(jpan[0],BorderLayout.WEST);
        cc.add(jpan[1],BorderLayout.CENTER);
    cc.add(jpan[2],BorderLayout.SOUTH); //添加jpan[0]上的内容 
    jpan[0].setLayout(new BorderLayout()); 
    jtfwest=new JTextArea(20,15); 

    //添加滚动条
    jspw=new JScrollPane();  

    //设置什么时候显示滚动条 
    jspw.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);

    jspw.getViewport().add(jtfwest);         
        jpan[0].add(jspw,BorderLayout.CENTER);
        
         //设置自动换行,自动换行则不会出现横向的滚动条
    jtfwest.setLineWrap(true);       
        
    //添加jpan[1]上的内容 
    jpan[1].setLayout(new BorderLayout()); 
    jtfcenter=new JTextArea(20,35);
    jspc=new JScrollPane();
    jspc.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); 
    jspc.getViewport().add(jtfcenter);         
        jpan[1].add(jspc,BorderLayout.CENTER);
    jtfcenter.setLineWrap(true);  //添加jpan[2]上的内容 
    jpan[2].setLayout(new BorderLayout());
    jpan[3]=new JPanel();
    jlabel[0]=new JLabel("                                                                      ");
    jlabel[1]=new JLabel("           ");

    jbugb = new JButton("关闭");
    jbugb.addActionListener(this);//注册监听器 jbclear = new JButton("清空");
    jbclear.addActionListener(this); jbufs = new JButton("发送");
    jbufs.addActionListener(this);
    jbufs.setEnabled(false); jtfbottom = new JTextArea(5,49);
    //jtfbottom.addActionListener(this);

    jspb = new JScrollPane();
    jspb.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); 
    jspb.getViewport().add(jtfbottom);         
        jpan[2].add(jspb,BorderLayout.CENTER);
    jpan[2].add(jpan[3],BorderLayout.SOUTH);
    jpan[3].setLayout(new FlowLayout());

    jpan[3].add(jlabel[0]);

    jpan[3].add(jbufs);
    jpan[3].add(jbclear);
    //jpan[3].add(jlabel[1]);
    jpan[3].add(jbugb);
    jtfbottom.setLineWrap(true); 
          pack(); //默认容器大小与this.setSize(500,550)作用差不多
              //结束程序
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocation(330,100); //设置对话框的位置
               //设置可见
    jtfbottom.requestFocus(); //获得焦点
               this.setVisible(true); 

    }
    //实现发送监听器
    public void actionPerformed(ActionEvent e) {
    if(e.getActionCommand().equals("关闭")) //判断事件源的三种方法:3. e.getActionCommand.comparedTo("关闭")==0
    {
    System.exit(0);
        }

    if(e.getSource()==jbufs)
    {
    String s=jtfbottom.getText();
    sendData(s);
    //jtfcenter.setText(s);    }
    if(e.getSource()==jbclear){
     jtfbottom.setText(null);    }
       
    }
    //
    // connect to server
    private void connectToServer() throws IOException
    {      
       jtfcenter.setText("准备连接.......\n");   // create Socket to make connection to server
       client=new Socket(InetAddress.getByName(chatServer),5000);   // display connection information
       jtfcenter.append("已经连接到: "+client.getInetAddress().getHostName()+"!\n");
       jtfwest.append("\n主机"+client.getInetAddress().getHostName()+"在线\n");
    }private void getStreams() throws IOException
    {
       // set up output stream for objects
       output = new ObjectOutputStream(client.getOutputStream());   // flush output buffer to send header information
       output.flush();   // set up input stream for objects
       input=new ObjectInputStream(client.getInputStream());   jtfcenter.append("\n已获取 I/O 流\n");
    }// process connection with server
    private void processConnection()throws IOException{
       // enable enterField so client user can send messages
       jbufs.setEnabled(true);   // process messages sent from server
       do {      // read message and display it
          try {
             message=(String)input.readObject();
             jtfcenter.append("\n"+message);
             jtfcenter.setCaretPosition(jtfcenter.getText().length());
          }      // catch problems reading from server
          catch (ClassNotFoundException ClassNotFoundException){
             jtfcenter.append("\nUnknown object type received");
          }   } while (!message.equals("SERVER>>> TERMINATE"));}  // end method process connection// close streams and socket
    private void closeConnection() throws IOException
    {
       jtfcenter.append("\nClosing connection");
       output.close();
       input.close();
       client.close();
    }// send message to server
    private void sendData(String message)
    {
       // send object to server
       try {
          output.writeObject("CLIENT>>> "+message);
          output.flush();
          jtfcenter.append("\nCLIENT>>> "+message);
       }   // process problems sending object
       catch (IOException ioException) {
          jtfcenter.append("\nError writing object");
       }
    }
    public void runClient() 
    {
       // connect to server, get streams, process connection
       try {      // Step 1: Create a Socket to make connection
          connectToServer();      // Step 2: Get the input and output streams
          getStreams();      // Step 3: Process connection
          processConnection();      // Step 4: Close connection
          closeConnection();
       }   // server closed connection
       catch (EOFException eofException){
          System.out.println( "Server terminated connection" );
       }   // process problems communicating with server
       catch (IOException ioException){
          ioException.printStackTrace();
       }
    } public static void main(String[] args){
           TestChatClient application;    if (args.length==0)
           application = new TestChatClient("127.0.0.1");
        else
          application = new TestChatClient(args[0]);       application.runClient();
       }
    }
      

  2.   

    实现监听客户端请求的应该用线程实现,即将connection = server.accept();及数据交换的功能封装到另一个线程类中,来实现,而在frame()
    框架类中每次new()