javaswing-Socket-聊天室大作业

本文介绍了一个使用Java Swing和Socket编程实现的聊天室应用,包括服务器端和客户端的设计与实现细节。服务器端负责接收多个客户端的连接请求,管理和广播消息,而客户端能够连接到服务器,发送和接收消息。

大学生大作业聊天室-javaswing-Socket

  • 服务器端
package talk_Demo;
import java.awt.EventQueue;
import java.io.InputStream;

import javax.swing.JFrame;
import java.awt.FlowLayout;
import java.awt.CardLayout;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JScrollPane;
import java.awt.Component;
import javax.swing.Box;
import javax.swing.DefaultListModel;

import java.awt.Dimension;
import javax.swing.JProgressBar;
import javax.swing.JPasswordField;
import javax.swing.JToggleButton;
import javax.swing.JDesktopPane;
import javax.swing.JToolBar;
import javax.swing.JTextArea;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JFormattedTextField;
import javax.swing.border.TitledBorder;

import org.omg.CORBA.StringHolder;

import javax.swing.UIManager;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JTextPane;
import javax.swing.border.BevelBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.border.LineBorder;
import java.awt.Font;
import java.awt.List;

import javax.swing.border.MatteBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JSlider;
import java.awt.Scrollbar;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.renderable.RenderableImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.WatchEvent;
import java.nio.file.Watchable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;

public class Fuwuqi_Demo {

	private JFrame frame;
	private JTextArea duankou_f;			//服务器端口
	private JTextArea renshu_f;				//人数上限
	private JTextPane xiaoxi_f;				//发送消息
	private boolean isStart = false;		//判断服务器是否已经启动(默认未启动)
	ServerSocket ss = null;
	int DK = 0;
	int RS = 0;
	private JButton stop_f;
	private JTextArea mas_f;
	private JList online_f;
	private DefaultListModel<String> ListModel;
	private ArrayList<Clientuser>  onlineuers = new ArrayList<Clientuser>();
	BufferedReader reader;
	PrintWriter writer;
	private Fuwu t1 ;
	private JButton fas;
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Fuwuqi_Demo window = new Fuwuqi_Demo();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public Fuwuqi_Demo() {
		initialize();
	}
	/**************************************************线程1*******************************************************/
	public class Fuwu extends Thread  {
		private int RS;
		/**
		 * @return rS
		 */
		public int getRS() {
			return RS;
		}
		/**
		 * @param rS 要设置的 rS
		 */
		public void setRS(int rS) {
			RS = rS;
		}
		public Fuwu(int rS) {
			super();
			setRS(rS);
		}
		public void run(){
			while (isStart) {
				try {
					/********************************************接收客服端的信息***************************************************************/
					Socket s= ss.accept();
					InputStream in = s.getInputStream();
					OutputStream out = s.getOutputStream();
					reader = new BufferedReader(new InputStreamReader(in));
					writer = new PrintWriter(out);
					String info = reader.readLine();
					System.out.println(info);
					int onlineNo = ListModel.size();
					if (onlineNo  == 30) {
						writer.println("超过最大人数,连接失败");
						writer.flush();
						//关闭窗口
						writer.close();
						reader.close();
						out.close();
						in.close();
						s.close();
					} else {
						
						mas_f.append("客服端连接成功"+info+"\n");
						writer.println("SUCCESS@"+info+"与服务器连接成功");
						writer.flush();
						StringTokenizer st = new StringTokenizer(info, "@");
						String ip = st.nextToken();
						String name = st.nextToken();
						ListModel.addElement(name);
						//将在线的人姓名发送给新上线的客服
						String temp = "";
						for(int i=0; i<ListModel.size();i++) {
							String username = ListModel.getElementAt(i);
							if (i == 0) {
								temp = username;
							}else {
								temp = temp + "@" +username;
							}

						}
						String onlineuser = "USERLIST@" + onlineNo + "@" +temp;
						writer.println(onlineuser);
						writer.flush();
						
						for(Clientuser clientuser:onlineuers) {
						PrintWriter w =  clientuser.getWriter();
						w.println("ADD@" +name);
						w.flush();
						}
						Sent sent = new  Sent();
						sent.start();
						Clientuser clientuser = new  Clientuser();
						clientuser.setIp(ip);
						clientuser.setName(name);
						clientuser.setReader(reader);
						clientuser.setWriter(writer);
						clientuser.setSocket(s);
						clientuser.setSent(sent);
						onlineuers.add(clientuser);
						
					}
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
		}
	}
public class Sent extends Thread{
	public void run() {
		try {
			while (isStart) {
				String info = reader.readLine();
				if (info!=null&&!info.equals("")) {
					StringTokenizer st = new StringTokenizer(info, "@");
					String command = st.nextToken();
					if (command.equals("ALL")) {
						String mess = st.nextToken();
						mas_f.append("\n"+mess);
						for(Clientuser clientuser:onlineuers) {
							PrintWriter w =  clientuser.getWriter();
							w.println(info);
							w.flush();
							}
					}
					else if (command.equals("CLOSE")) {
						String username = st.nextToken();
						mas_f.append(username+"下线");
						for(Clientuser clientUser:onlineuers) {
							if(!clientUser.getName().equals(username)) {
								//下线用户不是当前在线用户,转发该用户下线
								PrintWriter w = clientUser.getWriter();
								w.println("DELETE@"+username);
								w.flush();
							}else {
								clientUser.getSent().interrupt();
								System.out.println("1111111111111111111");
							}
							ListModel.removeElement(username);
							}
					}
					
				}
			}
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setTitle("\u670D\u52A1\u5668\u7AEF");
		frame.setBounds(550,100, 800, 710);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);

		JPanel panel = new JPanel();
		panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "\u914D\u7F6E\u4FE1\u606F", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		panel.setBounds(0, 13, 782, 79);
		frame.getContentPane().add(panel);

		JLabel label = new JLabel("\u4EBA\u6570\u4E0A\u9650\uFF1A");

		JLabel label_1 = new JLabel("\u7AEF\u53E3\uFF1A");

		JButton start_f = new JButton("\u542F\u52A8");
		start_f.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
			}
		});
		start_f.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				if (isStart) {
					JOptionPane.showMessageDialog(frame, "服务不能重复启动", "警告",JOptionPane.WARNING_MESSAGE );
					return;
				}else {
					String dk = duankou_f.getText();
					if (dk.trim().equals(" ")) {
						JOptionPane.showMessageDialog(frame, "请输入端口号", "警告",JOptionPane.WARNING_MESSAGE );
						return;
					}

					try {
						DK = Integer.parseInt(dk);
					} catch (NumberFormatException e) {
						// TODO 自动生成的 catch 块
						JOptionPane.showMessageDialog(frame, "端口号请输入数字", "提示",JOptionPane.WARNING_MESSAGE );
					}
					if (DK <8800) {
						JOptionPane.showMessageDialog(frame, "端口号必须大于8800", "提示",JOptionPane.WARNING_MESSAGE );
						return;
					}else {
						String rs = renshu_f.getText();
						if (rs.trim().equals("")) {
							JOptionPane.showMessageDialog(frame, "请输入人数", "警告",JOptionPane.WARNING_MESSAGE );
							return;
						}

						try {
							RS = Integer.parseInt(rs);
						} catch (NumberFormatException e) {
							// TODO 自动生成的 catch 块
							JOptionPane.showMessageDialog(frame, "人数请输入数字", "提示",JOptionPane.WARNING_MESSAGE );
						}
						if (RS>30) {
							JOptionPane.showMessageDialog(frame, "输入人数小于30", "提示",JOptionPane.WARNING_MESSAGE );
							return;
						}else {
							/*******************************************启动服务器********************************************************/		
							try {
								ss= new ServerSocket(DK);						//服务器已经启动
								isStart = true;	
								t1  = new Fuwu(RS);
								t1.start();										//线程						
								JOptionPane.showMessageDialog(frame, "启动成功", "提示",JOptionPane.WARNING_MESSAGE );
								start_f.setEnabled(false);
								stop_f.setEnabled(true);
							} catch (IOException e) {
								// TODO 自动生成的 catch 块
								e.printStackTrace();
							}
						}
					}
				}
			}
		});

		stop_f = new JButton("\u65AD\u5F00");
		stop_f.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				for(Clientuser clientUser:onlineuers) {
					//发送服务器下线消息
					PrintWriter wt = clientUser.getWriter();
					wt.println("CLOSE");
					wt.flush();
					//线程关闭
					clientUser.getSent().interrupt();
					//通道关闭
					try {
						clientUser.getWriter().close();
						clientUser.getReader().close();
						clientUser.getIn().close();
						clientUser.getOut().close();
						clientUser.getSocket().close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					//2、关闭上线提醒线程
					t1.interrupt();
					isStart=false;
					ListModel.removeAllElements();
					mas_f.removeAll();
					start_f.setEnabled(true);
					stop_f.setEnabled(false);
					fas.setEnabled(false);
				} 
			}
		});
		stop_f.setEnabled(false);																	//暂时禁用停止按钮

		duankou_f = new JTextArea();
		duankou_f.setFont(new Font("Monospaced", Font.PLAIN, 18));
		duankou_f.setText("8888");

		renshu_f = new JTextArea();
		renshu_f.setText("30");
		renshu_f.setFont(new Font("Monospaced", Font.PLAIN, 18));
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(
				gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup()
						.addContainerGap()
						.addComponent(label)
						.addGap(18)
						.addComponent(renshu_f, GroupLayout.PREFERRED_SIZE, 127, GroupLayout.PREFERRED_SIZE)
						.addGap(59)
						.addComponent(label_1)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(duankou_f, GroupLayout.PREFERRED_SIZE, 127, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
						.addComponent(start_f, GroupLayout.PREFERRED_SIZE, 85, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(stop_f, GroupLayout.PREFERRED_SIZE, 85, GroupLayout.PREFERRED_SIZE)
						.addGap(79))
				);
		gl_panel.setVerticalGroup(
				gl_panel.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panel.createSequentialGroup()
						.addContainerGap()
						.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
								.addComponent(label_1)
								.addComponent(duankou_f, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE))
						.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
				.addGroup(gl_panel.createSequentialGroup()
						.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
								.addComponent(stop_f)
								.addComponent(start_f))
						.addContainerGap())
				.addGroup(gl_panel.createSequentialGroup()
						.addContainerGap()
						.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
								.addComponent(label)
								.addComponent(renshu_f, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE))
						.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
				);
		panel.setLayout(gl_panel);

		JPanel panel_1 = new JPanel();
		panel_1.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "\u5728\u7EBF\u4EBA\u6570", TitledBorder.LEADING, TitledBorder.TOP, null, Color.DARK_GRAY));
		panel_1.setBounds(10, 105, 212, 409);
		frame.getContentPane().add(panel_1);

		ListModel = new  DefaultListModel<String>();
		online_f  = new  JList(ListModel);
		GroupLayout gl_panel_1 = new GroupLayout(panel_1);
		gl_panel_1.setHorizontalGroup(
				gl_panel_1.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_1.createSequentialGroup()
						.addContainerGap()
						.addComponent(online_f, GroupLayout.PREFERRED_SIZE, 179, GroupLayout.PREFERRED_SIZE)
						.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
				);
		gl_panel_1.setVerticalGroup(
				gl_panel_1.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panel_1.createSequentialGroup()
						.addContainerGap(36, Short.MAX_VALUE)
						.addComponent(online_f, GroupLayout.PREFERRED_SIZE, 346, GroupLayout.PREFERRED_SIZE))
				);
		panel_1.setLayout(gl_panel_1);

		JPanel panel_4 = new JPanel();
		panel_4.setBorder(new TitledBorder(null, "\u6D88\u606F\u533A", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel_4.setBounds(230, 105, 552, 409);
		frame.getContentPane().add(panel_4);

		mas_f = new JTextArea();
		GroupLayout gl_panel_4 = new GroupLayout(panel_4);
		gl_panel_4.setHorizontalGroup(
				gl_panel_4.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_4.createSequentialGroup()
						.addComponent(mas_f, GroupLayout.PREFERRED_SIZE, 478, GroupLayout.PREFERRED_SIZE)
						.addContainerGap(62, Short.MAX_VALUE))
				);
		gl_panel_4.setVerticalGroup(
				gl_panel_4.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panel_4.createSequentialGroup()
						.addContainerGap(22, Short.MAX_VALUE)
						.addComponent(mas_f, GroupLayout.PREFERRED_SIZE, 360, GroupLayout.PREFERRED_SIZE))
				);
		panel_4.setLayout(gl_panel_4);

		JPanel panel_5 = new JPanel();
		panel_5.setBorder(new TitledBorder(null, "\u5199\u6D88\u606F", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel_5.setBounds(14, 527, 768, 106);
		frame.getContentPane().add(panel_5);

		xiaoxi_f = new JTextPane();
		xiaoxi_f.setFont(new Font("宋体", Font.PLAIN, 18));

		fas = new JButton("\u53D1\u9001");
		fas.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String sendMessage = xiaoxi_f.getText();
				for(Clientuser clientUser:onlineuers) {
					PrintWriter w = clientUser.getWriter();
					w.println("ALL@服务器说:"+sendMessage);
					w.flush();
				} 
				mas_f.append(sendMessage);
			}
		});
		GroupLayout gl_panel_5 = new GroupLayout(panel_5);
		gl_panel_5.setHorizontalGroup(
				gl_panel_5.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_5.createSequentialGroup()
						.addComponent(xiaoxi_f, GroupLayout.PREFERRED_SIZE, 606, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.UNRELATED)
						.addComponent(fas, GroupLayout.PREFERRED_SIZE, 106, GroupLayout.PREFERRED_SIZE)
						.addContainerGap(30, Short.MAX_VALUE))
				);
		gl_panel_5.setVerticalGroup(
				gl_panel_5.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_5.createSequentialGroup()
						.addContainerGap()
						.addComponent(xiaoxi_f, GroupLayout.PREFERRED_SIZE, 37, GroupLayout.PREFERRED_SIZE)
						.addContainerGap(29, Short.MAX_VALUE))
				.addGroup(gl_panel_5.createSequentialGroup()
						.addComponent(fas, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addGap(26))
				);
		panel_5.setLayout(gl_panel_5);
	}
}


  IP正则判断类
 
import java.util.regex.Matcher;  
import java.util.regex.Pattern;  
 

public class IpAddress   
{  
    public static class IpAdd  
    {  
        public boolean isIP(String addr)  
        {  
            if(addr.length() < 7 || addr.length() > 15 || "".equals(addr))  
            {  
                return false;  
            }   
          
            String rexp = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";  
 
            Pattern pat = Pattern.compile(rexp);    
 
            Matcher mat = pat.matcher(addr);    
 
            boolean ipAddress = mat.find();  
 
            return ipAddress;  
        }  
    }
}


1. 保存通道
2. package talk_Demo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

import talk_Demo.Fuwuqi_Demo.Fuwu;
import talk_Demo.Fuwuqi_Demo.Sent;

public class Clientuser {
	private String ip;
	private String name;
	private BufferedReader reader;
	private PrintWriter writer;
	private Socket socket;
	private Sent sent;
	private InputStream in;
	private OutputStream out;
	/**
	 * @return ip
	 */
	public String getIp() {
		return ip;
	}
	/**
	 * @param ip 要设置的 ip
	 */
	public void setIp(String ip) {
		this.ip = ip;
	}
	/**
	 * @return name
	 */
	public String getName() {
		return name;
	}
	/**
	 * @param name 要设置的 name
	 */
	public void setName(String name) {
		this.name = name;
	}
	/**
	 * @return reader
	 */
	public BufferedReader getReader() {
		return reader;
	}
	/**
	 * @param reader 要设置的 reader
	 */
	public void setReader(BufferedReader reader) {
		this.reader = reader;
	}
	/**
	 * @return writer
	 */
	public PrintWriter getWriter() {
		return writer;
	}
	/**
	 * @param writer 要设置的 writer
	 */
	public void setWriter(PrintWriter writer) {
		this.writer = writer;
	}
	/**
	 * @return socket
	 */
	public Socket getSocket() {
		return socket;
	}
	/**
	 * @param socket 要设置的 socket
	 */
	public void setSocket(Socket socket) {
		this.socket = socket;
	}
	/**
	 * @return clientuser
	 */
	/**
	 * @return t1
	 */
	/**
	 * @return in
	 */
	public InputStream getIn() {
		return in;
	}
	/**
	 * @param in 要设置的 in
	 */
	public void setIn(InputStream in) {
		this.in = in;
	}
	/**
	 * @return out
	 */
	public OutputStream getOut() {
		return out;
	}
	/**
	 * @param out 要设置的 out
	 */
	public void setOut(OutputStream out) {
		this.out = out;
	}
	/**
	 * @return sent
	 */
	public Sent getSent() {
		return sent;
	}
	/**
	 * @param sent 要设置的 sent
	 */
	public void setSent(Sent sent) {
		this.sent = sent;
	}
	
}

客服端
package talk_Demo;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;

import org.omg.CORBA.StringHolder;

import talk_Demo.IpAddress.IpAdd;

import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.Color;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JSplitPane;
import javax.swing.JList;
import javax.swing.JOptionPane;

import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class KeFuDuan_one {

	private JFrame frame;
	private JTextField duankou_k;                                         //端口text
	Socket ss ;															  //开启服务器ss
	private JTextArea name;												  //名字text
	private JTextArea ip_k;												  //ip文本框
	ServerSocket n2;													  //开启服务器n2 (线程里面的)
	int DK ;															  //保存的int(整形)端口号
	private boolean isConnect = false;									  //判断服务器是否开启
	private JButton lianije_k;											  //连接按钮
	private JButton duankai_k;											  //按钮	
	private JList zaixian;
	private DefaultListModel<String> ListModel;
	private JTextArea textArea;
	BufferedReader reader;
	PrintWriter writer;
	String info;
	InputStream in;
	OutputStream out;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					KeFuDuan_one window = new KeFuDuan_one();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public KeFuDuan_one() {
		initialize();
	}
	public class Accepte extends Thread{
		public void run(){
			while (isConnect) {
				String na = name.getText();
				try {
					info = reader.readLine();
					StringTokenizer st = new StringTokenizer(info,"@");
					String command = st.nextToken();
					System.out.println(info);
					if(command.equals("SUCCESS")) {
						textArea.append("你与服务器连接成功");
					}else if(command.equals("USERLIST")) {
						String no = st.nextToken();
						try {
							int onlineno = Integer.parseInt(no);
							for(int i=0;i<onlineno;i++) {
								String username = st.nextToken();
								ListModel.addElement(username);
							}
						}catch(NumberFormatException e) {
							e.printStackTrace();
						}
						
					}else if(command.equals("ADD")){
						String username = st.nextToken();
						ListModel.addElement(username);
						textArea.append("\n"+username+"上线!");
					}else if(command.equals("ALL")){
						String message = st.nextToken();
						textArea.append("\n"+message);
					}else if(command.equals("DELETE")) {
						String username = st.nextToken();
						textArea.append("\n"+username+"下线");
						ListModel.removeElement(username);
					}else if(command.equals("CLOSE")) {
						ListModel.removeAllElements();
						textArea.removeAll();
						textArea.append("服务器下线");
						isConnect = false;
						Accepte.interrupted();
						duankai_k.setEnabled(false);
						
					}
						else {
					}
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
	}
	
	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosed(WindowEvent arg0) {
				//1、发送下线消息
				String username = name.getText();
				writer.println("CLOSE@"+username);
				writer.flush();
				//2、关闭通道
				try {
					writer.close();
					reader.close();
					out.close();
					in.close();
					if(ss!=null) {
						ss.close();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		frame.setTitle("\u5BA2\u670D\u7AEF");
		frame.setBounds(550,100, 818, 587);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		JPanel panel = new JPanel();
		panel.setForeground(Color.LIGHT_GRAY);
		GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
		groupLayout.setHorizontalGroup(
				groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
						.addComponent(panel, GroupLayout.PREFERRED_SIZE, 780, GroupLayout.PREFERRED_SIZE)
						.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
				);
		groupLayout.setVerticalGroup(
				groupLayout.createParallelGroup(Alignment.LEADING)
				.addComponent(panel, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 766, Short.MAX_VALUE)
				);

		JPanel panel_1 = new JPanel();
		panel_1.setBorder(new TitledBorder(null, "\u8FDE\u63A5\u6837\u5F0F", TitledBorder.LEADING, TitledBorder.TOP, null, null));

		JSplitPane splitPane = new JSplitPane();
		splitPane.setResizeWeight(0.25);

		JPanel panel_4 = new JPanel();
		panel_4.setBorder(new TitledBorder(null, "\u6D88\u606F\u53D1\u9001\u533A", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(
				gl_panel.createParallelGroup(Alignment.TRAILING)
				.addGroup(Alignment.LEADING, gl_panel.createSequentialGroup()
						.addContainerGap()
						.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
								.addComponent(panel_4, GroupLayout.PREFERRED_SIZE, 748, GroupLayout.PREFERRED_SIZE)
								.addComponent(splitPane, GroupLayout.DEFAULT_SIZE, 752, Short.MAX_VALUE)
								.addComponent(panel_1, GroupLayout.DEFAULT_SIZE, 752, Short.MAX_VALUE))
						.addContainerGap())
				);
		gl_panel.setVerticalGroup(
				gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup()
						.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 97, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(splitPane, GroupLayout.PREFERRED_SIZE, 323, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.UNRELATED)
						.addComponent(panel_4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addContainerGap(215, Short.MAX_VALUE))
				);

		JTextArea xiaoxi_k = new JTextArea();
		xiaoxi_k.setFont(new Font("Monospaced", Font.PLAIN, 18));

		JButton sent_k = new JButton("\u53D1\u9001");//发送消息
		sent_k.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String se =textArea.getText();
				if (se.trim().equals("")) {
					JOptionPane.showMessageDialog(frame, "不能为空", "警告",JOptionPane.WARNING_MESSAGE );
				} else {
					String sent = xiaoxi_k.getText();
					String  na = name.getText();
					writer.println("ALL@"+ na +"说:"+ sent);
					writer.flush();
				}
			}
		});
		sent_k.setFont(new Font("宋体", Font.PLAIN, 18));
		GroupLayout gl_panel_4 = new GroupLayout(panel_4);
		gl_panel_4.setHorizontalGroup(
				gl_panel_4.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_4.createSequentialGroup()
						.addContainerGap()
						.addComponent(xiaoxi_k, GroupLayout.PREFERRED_SIZE, 619, GroupLayout.PREFERRED_SIZE)
						.addGap(18)
						.addComponent(sent_k)
						.addContainerGap(34, Short.MAX_VALUE))
				);
		gl_panel_4.setVerticalGroup(
				gl_panel_4.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_4.createSequentialGroup()
						.addGroup(gl_panel_4.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_panel_4.createSequentialGroup()
										.addContainerGap()
										.addComponent(xiaoxi_k, GroupLayout.PREFERRED_SIZE, 43, GroupLayout.PREFERRED_SIZE))
								.addGroup(gl_panel_4.createSequentialGroup()
										.addGap(21)
										.addComponent(sent_k)))
						.addContainerGap(15, Short.MAX_VALUE))
				);
		panel_4.setLayout(gl_panel_4);

		JPanel panel_2 = new JPanel();
		panel_2.setBorder(new TitledBorder(null, "\u5728\u7EBF\u4EBA\u6570", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		splitPane.setLeftComponent(panel_2);

		ListModel = new  DefaultListModel<String>();
		zaixian = new JList(ListModel);
		GroupLayout gl_panel_2 = new GroupLayout(panel_2);
		gl_panel_2.setHorizontalGroup(
				gl_panel_2.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_2.createSequentialGroup()
						.addContainerGap()
						.addComponent(zaixian, GroupLayout.PREFERRED_SIZE, 154, GroupLayout.PREFERRED_SIZE)
						.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
				);
		gl_panel_2.setVerticalGroup(
				gl_panel_2.createParallelGroup(Alignment.LEADING)
				.addGroup(Alignment.TRAILING, gl_panel_2.createSequentialGroup()
						.addContainerGap(27, Short.MAX_VALUE)
						.addComponent(zaixian, GroupLayout.PREFERRED_SIZE, 254, GroupLayout.PREFERRED_SIZE)
						.addContainerGap())
				);
		panel_2.setLayout(gl_panel_2);

		JPanel panel_3 = new JPanel();
		panel_3.setBorder(new TitledBorder(null, "\u804A\u5929\u533A", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		splitPane.setRightComponent(panel_3);

		textArea = new JTextArea();
		GroupLayout gl_panel_3 = new GroupLayout(panel_3);
		gl_panel_3.setHorizontalGroup(
				gl_panel_3.createParallelGroup(Alignment.TRAILING)
				.addGroup(Alignment.LEADING, gl_panel_3.createSequentialGroup()
						.addContainerGap()
						.addComponent(textArea, GroupLayout.PREFERRED_SIZE, 473, GroupLayout.PREFERRED_SIZE)
						.addContainerGap(28, Short.MAX_VALUE))
				);
		gl_panel_3.setVerticalGroup(
				gl_panel_3.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_3.createSequentialGroup()
						.addContainerGap()
						.addComponent(textArea, GroupLayout.PREFERRED_SIZE, 272, GroupLayout.PREFERRED_SIZE)
						.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
				);
		panel_3.setLayout(gl_panel_3);

		JLabel label = new JLabel("\u7AEF\u53E3\uFF1A");
		label.setFont(new Font("宋体", Font.PLAIN, 18));

		duankou_k = new JTextField();
		duankou_k.setText("8888");
		duankou_k.setFont(new Font("宋体", Font.PLAIN, 18));
		duankou_k.setSelectionColor(Color.RED);
		duankou_k.setColumns(10);

		JLabel label_1 = new JLabel("\u670D\u52A1\u5668\uFF1A");
		label_1.setFont(new Font("宋体", Font.PLAIN, 18));

		ip_k = new JTextArea();
		ip_k.setText("127.0.0.1");
		ip_k.setFont(new Font("Monospaced", Font.PLAIN, 18));

		JLabel label_2 = new JLabel("\u59D3\u540D\uFF1A");
		label_2.setFont(new Font("宋体", Font.PLAIN, 18));

		name = new JTextArea();
		name.setFont(new Font("Monospaced", Font.PLAIN, 18));

		lianije_k = new JButton("\u8FDE\u63A5");
		/**************************************************************************客服端连接服务器*********************************************************************************/
		lianije_k.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				String dk = duankou_k.getText();
				String ip = ip_k.getText();
				String  na = name.getText();
				DK = Integer.parseInt(dk);
				if (dk.trim().equals("")) {
					JOptionPane.showMessageDialog(frame, "请输入端口号", "警告",JOptionPane.WARNING_MESSAGE );
					return;
				}
				else if (DK != 8888) {
					JOptionPane.showMessageDialog(frame, "端口为8888", "提示",JOptionPane.WARNING_MESSAGE );
				} else {
					IpAdd ipAdd = new IpAdd();
					if (ipAdd.isIP(ip) == false){
						JOptionPane.showMessageDialog(frame, "ip为127.0.0.1", "提示",JOptionPane.WARNING_MESSAGE );
					} else {
						try {
							Socket n3 = new Socket("127.0.0.1",DK);	
							in = n3.getInputStream();
							out = n3.getOutputStream();
							writer = new PrintWriter(out);
							reader = new BufferedReader(new InputStreamReader(in));
							String localIp =n3.getLocalAddress().getHostAddress(); 
							writer.println( localIp +"@" + na); 
							writer.flush(); 
							lianije_k.setEnabled(false);
							duankai_k.setEnabled(true);
							isConnect = true;
							Accepte accepte = new Accepte();
							accepte.start();
							lianije_k.setEnabled(false);
						} catch (IOException e) {
							// TODO 自动生成的 catch 块
							JOptionPane.showMessageDialog(frame, "连接失败", "提示",JOptionPane.WARNING_MESSAGE );
							e.printStackTrace();
						}
					}
				}
			}
		});
		lianije_k.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
			}
		}); 
		lianije_k.setFont(new Font("宋体", Font.PLAIN, 18));

		duankai_k = new JButton("\u65AD\u5F00");
		/*******************************************************断开****************************************************************************************/
		duankai_k.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String username = name.getText();
				String message = "CLOSE@"+username;
				writer.println(message);
				writer.flush();
				//2、关闭通道
				try {
					writer.close();
					reader.close();
					writer.close();
					reader.close();
					if(ss!=null) {
						ss.close();
					}
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				isConnect=false;
				Accepte.interrupted();
				ListModel.removeAllElements();
				textArea.removeAll();
			}
		});
		duankai_k.setEnabled(false);
		duankai_k.setFont(new Font("宋体", Font.PLAIN, 18));
		GroupLayout gl_panel_1 = new GroupLayout(panel_1);
		gl_panel_1.setHorizontalGroup(
				gl_panel_1.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_1.createSequentialGroup()
						.addContainerGap()
						.addComponent(label, GroupLayout.PREFERRED_SIZE, 62, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(duankou_k, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(label_1)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(ip_k, GroupLayout.PREFERRED_SIZE, 99, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(label_2)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(name, GroupLayout.PREFERRED_SIZE, 156, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(lianije_k)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(duankai_k)
						.addContainerGap(83, Short.MAX_VALUE))
				);
		gl_panel_1.setVerticalGroup(
				gl_panel_1.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_1.createSequentialGroup()
						.addContainerGap()
						.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
								.addComponent(label, GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE)
								.addComponent(duankou_k, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(label_1)
								.addComponent(ip_k, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(label_2)
								.addComponent(name, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
								.addComponent(lianije_k)
								.addComponent(duankai_k))
						.addContainerGap(25, Short.MAX_VALUE))
				);
		panel_1.setLayout(gl_panel_1);
		panel.setLayout(gl_panel);
		frame.getContentPane().setLayout(groupLayout);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值