java实现多人聊天(多线程+界面)

java实现多人聊天(多线程+界面)_第1张图片

java实现多人聊天(多线程+界面)_第2张图片

package chat;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.*;

public class Login extends JFrame
{
	 private String username = "123";
	 private String password = "123";
 
	 JFrame window;
	 JTextField user;
	 JTextField pwd;
	 JButton Login;
	 
	 
	 public Login()
	 {
		  window = new JFrame ("登陆界面");
		  window.setLayout(null);
		  window.setSize(600,500);
		  window.setLocationRelativeTo(null);
		  window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//closs
		  
		  window.setLayout(null);
		  window.setResizable(false);
		  
		  JLabel username_label = new JLabel("用户名");
		  username_label.setBounds(100,100,100,50);
		  window.add(username_label);
		  
		  JLabel password_label = new JLabel("密码");
		  password_label.setBounds(100,200,100,50);
		  window.add(password_label);
		  
		  user = new JTextField();
		  user.setBounds(150,100,300,50);
		  window.add(user);
		  
		  pwd = new JPasswordField();
		  pwd.setBounds(150,200,300,50);
		  window.add(pwd);
		  
		  Login = new JButton("登陆");
		  Login.setBounds(250,300,100,50);
		  window.add(Login);
		  
		  window.setVisible(true);
		  
		  this.username=user.getName();
		  
		  Login.addActionListener(new ActionListener()
			{
	            public void actionPerformed(ActionEvent e)
	            {
	            	String name=user.getText();
	      		  	String password=pwd.getText();
	      		  	if(password.equals("123"))
	      		  	{
	      		  		System.out.println("登陆成功");
	      				Client_window c1 = new Client_window(name);
	      				window.setVisible(false);
	      		  	}
	      		  	else
	      		  	{
	      		  		System.out.println("密码错误");
	      		  	}
	            }            
	        });
	 }
	 
 
}

 

package chat;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;

public class Server {

	public static void main(String[] args)
	{
		Server_window s1 = new Server_window();
	}
}
package chat;

import java.io.*;
import java.net.*;
import java.util.*;

public class Client {
	
	public static void main(String[] args)
	{
		Login g=new Login();
	}

}

 

package chat;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;

import chat.Server_window.ServerThread;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;

public class Client_window {
	
	String name;
	JFrame window;
    
    Socket socket;
    JTextArea showarea=null;
    
	DataInputStream is;
	DataOutputStream os;
    
    File dir;
    String fname;
    
	public Client_window()
	{
	}
	
	public Client_window(String name)
	{
		this.name=name;
		build();
	}
	
	void build()
	{
		window = new JFrame(name+"的聊天窗");
		window.setSize(600,700);
		window.setLocationRelativeTo(null);//窗口中间弹出
		window.setResizable(false);
		
		JPanel panel = new JPanel();//容器
		
		//显示框
		showarea = new JTextArea(30,50); 
		showarea.setLineWrap(true);//自动换行
		showarea.setEditable(false);//是否可以编辑
		
		// 创建滚动面板, 指定滚动显示的视图组件(showarea), 垂直滚动条一直显示, 水平滚动条从不显示
		JScrollPane scrollPane = new JScrollPane (showarea,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		
		//发送框
		JTextField textarea = new JTextField(40); 
		
		//发送按钮
		JButton btn = new JButton("发送");
		
		panel.add(scrollPane);//不用再添加showarea!!!
		panel.add(textarea);
		panel.add(btn);
		
		//文件传输控件
		JButton fbtn = new JButton("打开文件");
		JButton sbtn = new JButton("发送文件");
		JTextField farea = new JTextField(30); 
		farea.setEditable(false);//是否可以编辑
		panel.add(farea);
		panel.add(fbtn);
		panel.add(sbtn);
		
		window.setContentPane(panel);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭
		window.setVisible(true);
		
		//新建对象
		try
		{
			socket = new Socket("127.0.0.01",12321);
			is = new DataInputStream(socket.getInputStream());
			os = new DataOutputStream(socket.getOutputStream());
			
			new Thread(new Read(socket)).start();//创建从服务器读数据的线程
			String s=name+"上线了";
		
			os.writeUTF(s);//向服务器发送信息
			os.flush();//刷新		
            
		}catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
		
		//信息发送按钮响应事件
		btn.addActionListener(new ActionListener()
		{
            public void actionPerformed(ActionEvent e)
            {
                //获取输入框当前的内容,并加上用户姓名            
                String text = name+"说:"+textarea.getText();
                //写出数据
				try {
					os.writeUTF(text);
					os.flush();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
                textarea.setText("");//清空信息编辑框
            }            
        });
		
		//选择文件按钮响应事件
		fbtn.addActionListener(new ActionListener()
		{
            public void actionPerformed(ActionEvent e)
            {
            	JFileChooser jf=new JFileChooser();//创建文本选择框
            	jf.setCurrentDirectory(new File("E:\\javaprojects\\chat\\ClientFile"));//打开文本框位置
            	
            	int yes=jf.showOpenDialog(window);//判断是否选择了文件
            	if(yes==JFileChooser.APPROVE_OPTION)
            	{
	            	File f=jf.getSelectedFile();
	            	String path=f.getAbsolutePath();
	            	farea.setText(path);//将选择的文件路径显示到编辑框中
	            	dir=jf.getCurrentDirectory();//获取文件目录
	            	fname=jf.getSelectedFile().getName();//获取文件名字
            	}
            	

            	
            }            
        });
		
		//发送文件按钮响应事件
		sbtn.addActionListener(new ActionListener()
		{
            public void actionPerformed(ActionEvent e)
            {
            	if(dir!=null&&fname!=null)
            	{
            		File file =new File(dir,fname);
                	try 
                	{
                		String s=name+"发送了文件!";//向服务发送标志信息(不会写只能这样了~)
                    	os.writeUTF(s);
                    	os.flush();
                		
            			DataInputStream fis = new DataInputStream(new FileInputStream(file));	
                		
    					try {
    						
    						os.writeUTF(file.getName());//发送文件名字
    						os.flush();
    						
    						os.writeLong(file.length());//发送文件长度
    						os.flush();
    						
    						//发送文件
    						int len=-1;
    						byte[] buff=new byte[1024];
    						while((len=fis.read(buff))>0)
    						{
    							os.write(buff,0,len);
    							os.flush();
    						}
    						
    						fis.close();
    						showarea.append("发送完\n");
    						
    					} catch (IOException e1) {
    						// TODO Auto-generated catch block
    						e1.printStackTrace();
    					}
    					
    				} catch (FileNotFoundException e1) {
    					// TODO Auto-generated catch block
    					e1.printStackTrace();
    				} catch (IOException e3) {
    					// TODO Auto-generated catch block
    					e3.printStackTrace();
    				}
            	}

            }
        });
		
	}
	
	//读取线程
	class Read implements Runnable
	{
		Socket socket;
		
		public Read() {}
		
		public Read(Socket t)
		{
			this.socket = t;
		}
		public void run()
		{
			try
			{
				while(true)
				{
					String str="";
					str=is.readUTF();
					showarea.append(str+"\n");
					
					if(str.contains("发送了文件"))
					{
						String textname=is.readUTF();
						long totlen=is.readLong();
						byte[] buff = new byte[1024];
						int len = -1;
						long curlen=0;
						
						File filetot = new File("E:\\javaprojects\\chat\\"+name);//创建客户名字的目录
						if(!filetot.exists()) filetot.mkdir();
						
						File file = new File("E:\\javaprojects\\chat\\"+name+"\\"+textname);

						DataOutputStream fos=new DataOutputStream(new FileOutputStream(file));
						
						while((len=is.read(buff))>0)
						{
							curlen=curlen+len;
							fos.write(buff,0,len);
							fos.flush();
							if(curlen==totlen) break;//不break会卡住读
						}
						fos.close();
					}
					
				}
			}catch (IOException e) {
                e.printStackTrace();
            }
		}
	}
}
package chat;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class Server_window 
{
	//列表存全部连接的客户端
	public static ArrayList list=new ArrayList();
	
	ServerSocket server=null;
	ServerSocket fileserver=null;
	
	JFrame window;
	JTextArea showarea = null; 
	
	public Server_window()
	{
		build();
	}
	
	void build()
	{
		window = new JFrame("监视窗");
		window.setSize(600,700);
		window.setLocationRelativeTo(null);//窗口中间弹出
		window.setResizable(false);
		
		JPanel panel = new JPanel();
		
		//显示框
		showarea = new JTextArea(30,50);
		showarea.setLineWrap(true);//自动换行
		showarea.setEditable(false);//是否可以编辑
		
		// 创建滚动面板, 指定滚动显示的视图组件, 垂直滚动条一直显示, 水平滚动条从不显示
		JScrollPane scrollPane = new JScrollPane (showarea,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		
		panel.add(scrollPane);

		window.setContentPane(panel);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//closs
		window.setVisible(true);
		
		//连接
		try 
		{
			server=new ServerSocket(12321);
			while(true)
			{
				Socket socket=server.accept();

				list.add(socket);
				
				new Thread(new ServerThread(socket)).start();
			}
		} catch (IOException e) {
            e.printStackTrace();
        }
		
	}
	
	class ServerThread implements Runnable
	{
		Socket socket;
		
		//每个线程有自己的输入输出流!!
		DataInputStream is=null;
		DataOutputStream os=null;
		
		String name=null;
		
		public ServerThread() {}
		
		public ServerThread(Socket t)
		{
			this.socket = t;	
			try {
				is = new DataInputStream(this.socket.getInputStream());
				os = new DataOutputStream(this.socket.getOutputStream());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		public void run()
		{
			try
			{
				while(true)
				{
					String str=is.readUTF();
					
					//接收文件
					if(str.contains("发送了文件"))
					{
						byte[] buff = new byte[1024];
						int len = -1;
						long curlen=0;
								
						showarea.append("有文件传输!\n");
					
						String textname=is.readUTF();
						long totlen=is.readLong();
						for(Socket socket2:list)
						{
							DataOutputStream os2 = new DataOutputStream(socket2.getOutputStream());

							os2.writeUTF(str);
							os2.flush();
							
							os2.writeUTF(textname);
							os2.flush();
							
							os2.writeLong(totlen);
							os2.flush();
						}

						
						while((len=is.read(buff))>0)
						{
							curlen=curlen+len;
							for(Socket socket2:list)
							{
								//创建输出流
								DataOutputStream os2 = new DataOutputStream(socket2.getOutputStream());
			                    //输出信息
			                    os2.write(buff,0,len);//一定要len长度!!!
			                    //刷新
			                    os2.flush();
							}
							
							if(curlen==totlen) break;
						}
						
						showarea.append("转发完\n");
						
					}
					else 
					{
						//接收信息,第一次处理线程名字
						if(name==null) {
		                   //截取名称
		                    name=str.substring(0,str.indexOf("上"));
		                }
						showarea.append(str+"\n");
						for(Socket socket2:list)
						{
							//创建输出流
							DataOutputStream os2 = new DataOutputStream(socket2.getOutputStream());
		                    //输出信息
		                    os2.writeUTF(str);
		                    //刷新
		                    os2.flush();
						}
					
					}
					
				}
			}catch(IOException e) {
				//客户下线就移除
				list.remove(this.socket);
	            //循环输出信息
	            for(Socket socket2:list) {
	                //创建输出流
	                try {
	                	DataOutputStream os2 = new DataOutputStream(socket2.getOutputStream());
	                    //输出信息
	                    os2.writeUTF((name+"下线了"));
	                    //刷新
	                    os2.flush();
	                } catch (IOException e1) {
	                    // TODO Auto-generated catch block
	                    e1.printStackTrace();
	                }
	            }
			}
		}
	}
}

 

你可能感兴趣的:(java)