我的服务器端
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ChatServer {

 static final int PORT = 8888; // 端口号
 static List<Socket> list = new ArrayList<Socket>(); // 保存连接对象
 ExecutorService exec;
 ServerSocket server; public static void main(String[] args) {
new ChatServer();
} public ChatServer() {
try {
server = new ServerSocket(PORT);
exec = Executors.newCachedThreadPool();
System.out.println("服务器已启动!"); Socket client = null;
while (true) {
client = server.accept(); // 接收客户连接
list.add(client);
exec.execute(new ChatTask(client));
}
} catch (IOException e) {
e.printStackTrace();
}
} //static class ChatTask implements Runnable {
class ChatTask implements Runnable {
private Socket socket;
private BufferedReader br;
private PrintWriter pw;
private String msg; public ChatTask(Socket socket) throws IOException {
this.socket = socket;
br = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
msg = "【" + this.socket.getInetAddress() + "】进入聊天室!当前聊天室有【"
+ list.size() + "】人"; sendMessage();
} public void run() {
try {
while ((msg = br.readLine()) != null) {
if (msg.trim().equals("bye")) {
list.remove(socket);
br.close();
pw.close();
msg = "【" + socket.getInetAddress() + "】离开聊天室!当前聊天室有【"
+ list.size() + "】人";
socket.close(); sendMessage();
break;
} else {
msg = "【" + socket.getInetAddress() + "】说:" + msg;
sendMessage();
}
}
} catch (IOException e) {
e.printStackTrace();
}
} /**
 * 群发消息给聊天室的所有人
 */
private void sendMessage() throws IOException {
System.out.println(msg);
for (Socket client : list) {
pw = new PrintWriter(client.getOutputStream(), true);
pw.println(msg);
}
}
}
}

解决方案 »

  1.   

    我的客户端
    package Chat;import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    //import java.net.UnknownHostException;
    //import java.net.InetAddress;
    import java.io.*;
    import java.net.*;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    /**
    *实现了聊天室的基本布局
    */class TestChat extends JFrame implements ActionListener{ 
     //定义Chat所需的组件  
      
            //定义文本域
    JTextArea jtxa_GroupInfo = new JTextArea("群资料",5,13); 
    JTextArea jtxa_AcceptFile = new JTextArea("要接收的文件",5,13); 
    JTextArea jtxa_SendFile = new JTextArea("要发送的文件",5,13);
    TextAreaMenu jtxa_show,jtxa_input; //定义面板
    JPanel jpnl_NorthButton =new JPanel();
      JPanel jpnl_Center = new JPanel();   
      JPanel jpnl_CenterTextArea = new JPanel();
    JPanel jpnl_east = new JPanel();       
      JPanel jpnl_bottomTextArea = new JPanel();
    JPanel jpnl_CenterButton = new JPanel();       
      JPanel jpnl_CenterSouthButton = new JPanel();
    JPanel jpnl_west = new JPanel(); //最左边的那个按钮
    JPanel jpnl_eastTextArea = new JPanel();     
      JPanel jpnl_EastCenter = new JPanel();
    JPanel jpnl_EastCenterTextArea = new JPanel();
    JPanel jpnl_EastCenterButton = new JPanel();
    JPanel jpnl_EastSouthButton = new JPanel(); //定义空标签
    JLabel [] jlabel = new JLabel[7]; //定义滚动条
    JScrollPane jscp_EastGroupInfo = new JScrollPane(jtxa_GroupInfo);
    JScrollPane jscp_EastAcceptFile = new JScrollPane(jtxa_AcceptFile);
    JScrollPane jscp_EastSendFile = new JScrollPane(jtxa_SendFile);

    //定义按钮
    JButton jbtn_send = new JButton("发送");
    JButton jbtn_close = new JButton("关闭");
    JButton jbtn_font = new JButton("字体");
    JButton jbtn_expression = new JButton("表情");
    JButton jbtn_ChatPrivately = new JButton("私聊");
    JButton jbtn_SplashScreen = new JButton("闪屏震动");
    JButton jbtn_ChatLogs = new JButton("聊天记录");
    JButton jbtn_RemoteProcesdureCall = new JButton("远程协助");
    JButton jbtn_SendFile = new JButton("传输文件");
    JButton jbtn_VoiceChat = new JButton("语音聊天");
    JButton jbtn_VideoChat = new JButton("视频聊天");
    JButton jbtn_accept = new JButton("接收");
    JButton jbtn_refuse = new JButton("拒绝");
    JButton jbtn_cancel = new JButton("取消");
    JButton jbtn_clean = new JButton("清空消息"); String s="";
    FileDialog filepath; //用于传输文件时选择路径

    //定义客户端套接字变量
    private static final int PORT = 8888;
    private static ExecutorService exec = Executors.newCachedThreadPool();
     Socket clientSocket ;
     PrintWriter pw;
    /**
    *构造方法
    */ public TestChat(){  
      try{
    this.setTitle("Unite");
    this.setIconImage(java.awt.Toolkit.getDefaultToolkit().getImage(""));  //还没找到图片
              Container cc = this.getContentPane(); //返回此 applet 的 contentPane 对象。 

    filepath = new FileDialog(this,"选择文件");//产生一个能够打开文件,并可以选择文件的对话框

    //设置按钮的字体
    Font font=new Font("宋体",Font.PLAIN,13); 
    jbtn_close.setFont(font);
    jbtn_send.setFont(font);
    jbtn_font.setFont(font);
    jbtn_expression.setFont(font);
    jbtn_ChatPrivately .setFont(font);
    jbtn_SplashScreen.setFont(font);
    jbtn_ChatLogs.setFont(font);
    jbtn_RemoteProcesdureCall.setFont(font);
    jbtn_SendFile.setFont(font);
    jbtn_VoiceChat.setFont(font);
    jbtn_VideoChat.setFont(font);
    jbtn_accept.setFont(font);
    jbtn_refuse.setFont(font);
    jbtn_cancel.setFont(font);
    jbtn_clean.setFont(font); //定义空标签
    jlabel[0] = new JLabel("                                                            ");
    jlabel[1] = new JLabel("      ");
    jlabel[2] = new JLabel("        ");
    jlabel[3] = new JLabel("        ");
    jlabel[4] = new JLabel("        ");
    jlabel[5] = new JLabel("                                                                                      "   );
    jlabel[6] = new JLabel("                  "); //注册监听
    jbtn_close.addActionListener(this);
    jbtn_send.addActionListener(this);
    jbtn_clean.addActionListener(this); 
    jbtn_font.addActionListener(this);
    jbtn_ChatPrivately .addActionListener(this); 
    jbtn_SendFile.addActionListener(this); 

    //设置jpnl_Center背景色
    cc.setBackground(new Color(176,196,222));
    jpnl_NorthButton.setBackground(new Color(176,196,222));  
    jpnl_east.setBackground(new Color(176,196,222)); 
    jpnl_CenterButton.setBackground(new Color(176,196,222));
    jpnl_CenterSouthButton.setBackground(new Color(176,196,222));
    jpnl_EastCenterButton.setBackground(new Color(176,196,222));
    jpnl_EastSouthButton.setBackground(new Color(176,196,222));

    //设置cc上的布局
    setLayout(new BorderLayout(5,5));       
        cc.add(jpnl_NorthButton,BorderLayout.NORTH);
    cc.add(jpnl_west,BorderLayout.WEST);
        cc.add(jpnl_Center,BorderLayout.CENTER);
    cc.add(jpnl_east,BorderLayout.EAST); NorWestMyChat();
    CenEastChat(); pack(); //默认容器大小与this.setSize(500,550)作用差不多         
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭
    setLocation(100,50); //设置对话框的位置          
        this.setVisible(true);  //设置可见
    jtxa_input.requestFocus();//JTextArea 获取焦点 一般在设置可见之后      }
         catch(Exception e){
    e.printStackTrace(); 
         }
      try {
      clientSocket = new Socket("127.0.0.1", PORT);
    exec.execute(new Sender(clientSocket));
    //System.out.println("【" + socket.getInetAddress() + "】您好,欢迎来到07Java聊天室!");
    jtxa_show.append("【" + clientSocket.getInetAddress() + "】您好,欢迎来到07Java聊天室!\n"); BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    String msg;
    while ((msg = br.readLine()) != null) {
    //System.out.println(msg);
    jtxa_show.append(msg);
    }
    }catch (Exception e) {
    e.printStackTrace();
     } 
    } /**
    *整体布局为BorderLayout
    *添加北部和西部的组件
    *
    */
      

  2.   

    public void NorWestMyChat(){
    //给jpnl_NorthButton添加组件

    jpnl_NorthButton.add(jbtn_RemoteProcesdureCall);
    jpnl_NorthButton.add(jlabel[2]);
    jpnl_NorthButton.add(jbtn_SendFile);
    jpnl_NorthButton.add(jlabel[3]);
    jpnl_NorthButton.add(jbtn_VoiceChat);
    jpnl_NorthButton.add(jlabel[4]);
    jpnl_NorthButton.add(jbtn_VideoChat);
    jpnl_NorthButton.add(jlabel[5]);
    //给jpnl_west添加组件

    jpnl_west.setLayout(new BorderLayout());
    //jpnl_west.setLayout(null);   List list_left = null; //声明列表
    try{
    list_left=new List(20);
    Font font1=new Font("宋体",Font.PLAIN,19); 
    list_left.setFont(font1);
    }
    catch(HeadlessException he){
    System.out.println(he.toString());
    } list_left.add("成  员  列  表"); try{
    String sip=InetAddress.getLocalHost().getHostAddress();//获取本机IP,添加在列表中
    list_left.add(sip);
    }
    catch(UnknownHostException ep)
    {
    System.out.println(ep);
    } jpnl_west.add(list_left,BorderLayout.CENTER);
    //给jpnl_Center添加组件 jpnl_Center.setLayout(new BorderLayout(5,5)); 
    jpnl_Center.add(jpnl_CenterTextArea,BorderLayout.CENTER);     
    //给jpnl_EastCenterButton添加组件
    jpnl_EastCenterButton.setLayout(new GridLayout(1,2,10,2));
    jpnl_EastCenterButton.add(jbtn_accept);
    jpnl_EastCenterButton.add(jbtn_refuse); //给jpnl_EastCenterTextArea添加组件
    jpnl_EastCenterTextArea.setLayout(new BorderLayout());       
             jpnl_EastCenterTextArea.add(jscp_EastSendFile,BorderLayout.CENTER);
    jtxa_SendFile.setEditable(false);

    jpnl_EastCenterTextArea.add(jpnl_EastSouthButton,BorderLayout.SOUTH);

    //给jpnl_EastSouthButton添加组件

    jpnl_EastSouthButton.add(jlabel[6]);
    jpnl_EastSouthButton.add(jbtn_cancel);
    } /**
    *
    *添加中部和东部的组件
    *
    */ public void CenEastChat(){

    //给jpnl_CenterTextArea添加组件 jpnl_CenterTextArea.setLayout(new BorderLayout());
    jtxa_show = new TextAreaMenu(19,30);
    jtxa_show.init("jtfcenter");
    JScrollPane jscp_CenterShow = new JScrollPane(jtxa_show);
            jpnl_CenterTextArea.add(jscp_CenterShow,BorderLayout.CENTER);
    jtxa_show.setLineWrap(true); //设置自动换行,自动换行则不会出现横向的滚动条  
    jtxa_show.setEditable(false); //设置属性不可编辑 jpnl_CenterTextArea.add(jpnl_bottomTextArea,BorderLayout.SOUTH); //给jpnl_bottomTextArea添加组件
    jpnl_bottomTextArea.setLayout(new BorderLayout()); 
    jtxa_input = new TextAreaMenu(6,30);
    jtxa_input.init("jtfbottom");
    JScrollPane jscp_CenterInput = new JScrollPane(jtxa_input);
             jpnl_bottomTextArea.add(jscp_CenterInput,BorderLayout.CENTER);
    jtxa_input.setLineWrap(true); //设置自动换行,自动换行则不会出现横向的滚动条  
    jtxa_input.setEditable(true); //设置属性不可编辑
    jpnl_bottomTextArea.add(jpnl_CenterButton,BorderLayout.NORTH);
    jpnl_bottomTextArea.add(jpnl_CenterSouthButton,BorderLayout.SOUTH); //给jpnl_CenterButton添加组件
    jpnl_CenterButton.setLayout(new GridLayout(1,5,12,12));


    jpnl_CenterButton.add(jbtn_font);
    jpnl_CenterButton.add(jbtn_expression);
    jpnl_CenterButton.add(jbtn_SplashScreen);
    jpnl_CenterButton.add(jbtn_ChatLogs);
    jpnl_CenterButton.add(jbtn_ChatPrivately );

    //给jpnl_CenterSouthButton添加组件

    jpnl_CenterSouthButton.add(jbtn_clean);
    jpnl_CenterSouthButton.add(jlabel[0]);
    jpnl_CenterSouthButton.add(jbtn_close);
    jpnl_CenterSouthButton.add(jlabel[1]);
    jpnl_CenterSouthButton.add(jbtn_send);


    //给jpnl_east添加组件
    jpnl_east.setLayout(new GridLayout(3,1,2,2));

    jpnl_east.add(jpnl_eastTextArea);
    jpnl_east.add(jpnl_EastCenter);
    jpnl_east.add(jpnl_EastCenterTextArea);

    //给jpnl_eastTextArea添加组件
    jpnl_eastTextArea.setLayout(new BorderLayout());          
             jpnl_eastTextArea.add(jscp_EastGroupInfo,BorderLayout.CENTER);
    jtxa_GroupInfo.setEditable(false);

    //给jpnl_EastCenter添加组件
    jpnl_EastCenter.setLayout(new BorderLayout());          
             jpnl_EastCenter.add(jscp_EastAcceptFile,BorderLayout.CENTER);
    jtxa_AcceptFile.setEditable(false);

    jpnl_EastCenter.add(jpnl_EastCenterButton,BorderLayout.SOUTH); }
    //实现发送监听器
    public void actionPerformed(ActionEvent e) {
    if (e.getSource() == jbtn_font) { 
    Ziti zt = new Ziti(this); 
    jtxa_input.setFont(zt.f); 
    jtxa_show.setFont(zt.f); 
    }  if (e.getSource() == jbtn_ChatPrivately ) { 
    String ip = JOptionPane.showInputDialog("请输入对方的IP地址:",""); 
    }

     
    if(e.getActionCommand().equals("关闭")){
    System.exit(0);
        }
     
    if(e.getSource()==jbtn_send){

    s=jtxa_input.getText();
    sendData(s);
    //jtxa_show.setText(s);
    //new Sender(clientSocket,s).start();
    jtxa_input.setText("");    } if (e.getSource() == jbtn_clean) { 
    jtxa_show.setText(""); 
    s="";

    if (e.getSource() == jbtn_SendFile) { 
    filepath.setVisible(true);

    }

       /**
     * 客户端线程获取控制台输入消息
     */
    //static class Sender implements Runnable {
    class Sender implements Runnable {
    private Socket socket;
    // String msg;
    public Sender(Socket sockets) {
    this.socket = sockets;
    //msg=str;
    } public void run() {
    try {
    //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
     pw = new PrintWriter(socket.getOutputStream(), true); /* while (true) {
    msg = jtxa_input.getText();
    pw.println(msg); if (msg.trim().equals("bye")) {
    pw.close();
    //br.close();
    exec.shutdownNow();
    break;
    }
    }*/
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    }
    public void sendData(String msg){
    //while (true) {
    //msg = jtxa_input.getText();
    pw.println(msg); if (msg.trim().equals("bye")) {
    pw.close();
    //br.close();
    exec.shutdownNow();
    //break;
    }
    // }
    }
    /**
    *main方法
    */ public static void main(String[] args)throws Exception{
        TestChat f=new TestChat();
           }
    }