⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 client.java

📁 一个JAVA编写的客户端聊天程序,可进行远程传输文件,可进行聊天
💻 JAVA
字号:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
class Client extends JFrame implements Runnable,ActionListener
{
	JTextArea text;
	JTextField namefield;
	JFileChooser fileChooser;
	//Container con;
	String name,host,some;
	boolean connected;
	JButton send,sendfile,exit,connection;
	Socket socket;
	BufferedReader in=null;
	PrintWriter out=null;
	Thread thread;
	FileAccept thread1;
	public Client(String s) 
	{
		super(s);
	    tep.con=getContentPane();
		tep.con.setBackground(Color.gray);
		tep.con.setLayout(null);
		tep.con.validate();
		setBounds(100,100,470,380);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		fileChooser=new JFileChooser("e:/");
		JLabel label1=new JLabel("聊天系统",JLabel.CENTER);
		label1.setFont(new Font("楷体", Font.BOLD, 12));
		tep.con.add(label1);
		label1.setBounds(150,20,150,20);
		JLabel label2=new JLabel("目标主机地址:",JLabel.RIGHT);
		tep.con.add(label2);
		label2.setBounds(50,50,110,20);
		label2.setFont(new Font("楷体", Font.BOLD, 12));
		namefield=new JTextField(15);
		tep.con.add(namefield);
		namefield.setBounds(185,50,100,20);
		text=new JTextArea();
		JScrollPane a=new JScrollPane(text);
		tep.con.add(a);
		a.setBounds(20,80,420,80);
		a.setBackground(Color.white);
		tep.input=new JTextArea();
		JScrollPane b=new JScrollPane(tep.input);
		tep.con.add(b);
		b.setBounds(20,185,420,70);
		b.setBackground(Color.white);
		connection=new JButton("连接");
		tep.con.add(connection);
		connection.setBounds(85,280,70,30);
		send=new JButton("发送");
		tep.con.add(send);
		send.setBounds(177,280,70,30);
		send.setEnabled(false);
		sendfile=new JButton("请求文件");
		tep.con.add(sendfile);
		sendfile.setBounds(270,280,70,30);
		sendfile.setEnabled(false);
		exit=new JButton("Exit");
		tep.con.add(exit);
		exit.setBounds(360,280,70,30);
		JLabel label3=new JLabel("开始聊天ing",JLabel.LEFT);
		tep.con.add(label3);
		label3.setBounds(20,320,470,20);
		label3.setFont(new Font("楷体", Font.BOLD, 12));
		connection.addActionListener(this);
		send.addActionListener(this);
		sendfile.addActionListener(this);
		exit.addActionListener(this);
		thread=new Thread(this);	
	}
	public void run()
	{
		while(true)
		{
			try{
				String s=in.readLine();
				text.append("Server:"+s+"\n");
		        text.setCaretPosition((text.getText()).length());
		      }
		      catch(IOException e)
		      {
		      	namefield.setText("与服务器断开!");
		      	text.setText("请重新启动服务器!");
		      	send.setEnabled(false);
		      	sendfile.setEnabled(false);
		      	connection.setEnabled(true);
		      	break;
		      }
		}
	}
	public void actionPerformed(ActionEvent e)
	{
		if(e.getSource()==connection)
		{
			if(namefield.getText().equals("")){
				JOptionPane.showMessageDialog(this,"You must enter a name!","提示对话框",JOptionPane.INFORMATION_MESSAGE);
			}
			else
			{
				try{					
					name=namefield.getText();
					socket=new Socket(name,6666);
					in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
				    out=new PrintWriter(socket.getOutputStream());
					connected=true;
					sendfile.setEnabled(true);
					send.setEnabled(true);
					connection.setEnabled(false);
					namefield.setText("已连接服务器");
					text.setText("");
					thread.start();
					}
				catch(IOException ee){}
			}
		}
		if(e.getSource()==send)
		{
			if(tep.input.getText().equals(""))
			{
				JOptionPane.showMessageDialog(this,"发送内容不能为空","提示对话框",JOptionPane.INFORMATION_MESSAGE);
			}
			else
			{
				try{
					some=tep.input.getText();
					out.println(some);
					out.flush();
					text.append("Client:"+some+"\n");
			        text.setCaretPosition((text.getText()).length());
			        tep.input.setText("");
				}
			    catch(Exception ee)
			    {
			       tep.input.setText("请输入:");
			    }
			}
		}
		if(e.getSource()==sendfile)
		{
			try{
				out.println("客户请求发送文件,同意请按传送选择文件");
			    out.flush();
			}
			catch(Exception ee)
			{
				tep.input.setText("请求失败!请查看网络原因。。。");
			}
		    new FileAccept(6667).start();
		   // sendfile.setEnabled(false);
		}
		if(e.getSource()==exit)
		{
			System.exit(-1);
		}
	}
	public static void main(String args[])
	{
		Client win=new Client("聊天窗口");
	}
}
class FileAccept extends Thread
{
	ServerSocket server=null;
	int PORT;
	FileAccept(int port)
	{
		this.PORT=port;
	}
	public void run()
	{
	    try{
		server=new ServerSocket(PORT);
		while(true)
		{
			Socket s=server.accept();
			tep.input.setText("正在接收文件,请稍候。。。");
			new FileAcceptThread(s).start();
		}
	}
	catch(IOException e)
	{
		e.printStackTrace();
	}
	catch(Exception ee)
	{
		ee.printStackTrace();
	}
	finally
        {
            try
            {
                server.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
	}
}
class FileAcceptThread extends Thread
{
	Socket s=null;
	InputStream in=null;
	PrintWriter out=null;
	String serverMsg = null;
	FileAcceptThread(Socket s)
	{
		try{
			this.s = s;
            this.in = this.s.getInputStream();
            this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(this.s.getOutputStream())),true);
        } 
            catch (IOException e) 
            {
                e.printStackTrace();
            }
            this.start();
    }
	public void run()
	{
		String info  = "";
        try
        {
            while(true)   
            {
                Date befor = new Date();
                byte cmd[] = new byte[128];
                int b = 0;
                while(b<cmd.length)
                {
                    b += in.read(cmd, b, cmd.length-b);
                }
                int ends = 0;
                for(int i=0;i<cmd.length;i++)
                {
                    if(cmd[i]==-0)
                    {
                        ends = i;
                        break;
                    }
                }
                String cmds = new String(cmd,0,ends);
                if("cp".equals(cmds))
                {
                    byte[] filename = new byte[256];
                    b = 0;
                    while(b<cmd.length)
                    {
                        b += in.read(filename, b, filename.length-b);
                    }
                    ends = 0;
                    for(int i=0;i<cmd.length;i++)
                    {
                        if(filename[i]==-0)
                        {
                            ends = i;
                            break;
                        }
                    }
                    String filenames = new String(filename,0,ends);
                    filenames = "C://"+filenames;
                    File fileout = new File(filenames);
                    FileOutputStream fos = new FileOutputStream(fileout);
                    byte[] filesize = new byte[64];
                    b = 0;
                    while(b<filesize.length)
                    {
                        b += in.read(filesize, b, filesize.length-b);
                    } 
                    ends = 0;
                    for(int i=0;i<filesize.length;i++)
                    {
                        if(filesize[i]==-0)
                        {
                            ends = i;   
                            break;   
                        }
                    }
                    String filesizes = new String(filesize,0,ends);
                    int ta = Integer.parseInt(filesizes);
                    byte[] buf = new byte[1024*10];
                    while(true)
                    {
                        if(ta==0)
                        {
                            break;
                        }
                        int len = ta;
                        if(len>buf.length)
                        {
                            len = buf.length;
                        }
                        int rlen = in.read(buf, 0, len);
                        ta -=rlen;
                        if(rlen>0)
                        {
                            fos.write(buf,0,rlen);
                            fos.flush();  
                        }
                        else
                        {
                            break;
                        }
                    }
                    Date after = new Date();
                    long diff =after.getTime() - befor.getTime();
                    diff /=1000;
                    info = "传输完成!文件已经保存到:"+filenames+",文件大小:"+filesizes+"字节,"+"共用时间:"+diff+"秒";
                    int result = JOptionPane.showConfirmDialog(null, info, "文件传输", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE);
                    fos.close(); 
                    break;   
                }   
            }    
        }
        catch(Exception e)
        {
            e.printStackTrace();   
        }   
          try 
            {
                s.close();
            } 
            catch (IOException ex1)
            {
            }
        tep.input.setText("文件接收完毕,请打开C盘查看!");  
    }
}
class tep
{
	public static JTextArea input;
	public static Container con;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -