Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 959|回复: 0

java聊天器客户端 群聊私聊传文件

[复制链接]

该用户从未签到

发表于 2011-7-26 22:26:55 | 显示全部楼层 |阅读模式
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.StringReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class ClientWindow extends JFrame implements ActionListener,ListSelectionListener
{
    JList ClientList;
    JScrollPane ClientListPane;
    JTextArea ShowText;
    JTextField InputText;
    JScrollPane scroll;
    JButton SendButton;
    JButton SendFileButton;
    Socket serverSocket;
    RecvThread recvThread;
    DefaultListModel ClientListItems;
    String SendTarget;
    ClientWindow()
    {
        InitControl();
        Connect();
    }
    void Connect()
    {
        try
        {
            serverSocket = new Socket("127.0.0.1",8888);
            recvThread = new RecvThread(serverSocket,ShowText,ClientListItems);
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null, "连接服务器失败");
            System.exit(0);
        }
    }
    void InitControl()
    {
        ClientList = new JList();
        ClientListItems = new DefaultListModel();
        ClientList.setModel(ClientListItems);
        ClientListPane = new JScrollPane(ClientList);
        ClientListPane.setSize(200,400);
        ClientListPane.setLocation(410,5);
        
        ShowText = new JTextArea(500,250);
        scroll = new JScrollPane(ShowText);
        scroll.setSize(400,400);
        scroll.setLocation(5,5);
        ShowText.setEditable(false);
        
        SendButton = new JButton();
        SendButton.setText("发送");
        SendButton.setSize(80,20);
        SendButton.setLocation(410,410);
        
        SendFileButton = new JButton();
        SendFileButton.setText("文件");
        SendFileButton.setSize(80,20);
        SendFileButton.setLocation(500,410);
        
        InputText = new JTextField();
        InputText.setSize(400, 20);
        InputText.setLocation(5,410);
        add(SendButton);
        add(InputText);
        add(scroll);
        add(ClientListPane);
        add(SendFileButton);
        
        SendFileButton.addActionListener(this);
        SendButton.addActionListener(this);
        ClientList.addListSelectionListener(this);
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(null);
        setSize(620,465);
        setVisible(true);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource() == SendButton)
        {
            try
            {
                if(InputText.getText().equals(""))
                {
                    return;
                }
                if(SendTarget == null)
                {
                    SendTarget = "all";
                }
                DataOutputStream output = new DataOutputStream(serverSocket.getOutputStream());
                String str = "";
                str += "<xml>";
                str += "<mark>5</mark>";
                str += "<target>" + SendTarget + "</target>";
                str += "<content>" + InputText.getText().replaceAll("<", "<").replaceAll(">", ">") + "</content>";
                str += "</xml>";
                output.writeUTF(str);
            }
            catch(Exception e1)
            {
                e1.printStackTrace();
            }
        }
        if(e.getSource() == SendFileButton)
        {
            if(SendTarget == null)
            {
                JOptionPane.showMessageDialog(null, "请选择接收者");
                return;
            }
            if(SendTarget.equals("all"))
            {
                JOptionPane.showMessageDialog(null, "请选择接收者");
                return;
            }
            FileDialog filedialog = new FileDialog(this,"",FileDialog.LOAD);
            filedialog.setVisible(true);
            if(filedialog.getFile() == null)
            {
                return;
            }
            
            String filepath = filedialog.getDirectory()+filedialog.getFile();
            AcceptThread acceptThread = new AcceptThread(filepath);
            int port = acceptThread.port;
            String ip = acceptThread.ip;
            String file = filedialog.getFile();
            try
            {
                DataOutputStream output = new DataOutputStream(serverSocket.getOutputStream());
                String str = "";
                str += "<xml>";
                str += "<mark>7</mark>";
                str += "<target>" + SendTarget + "</target>";
                str += "<ip>" + ip + "</ip>";
                str += "<port>" + port + "</port>";
                str += "<file>" + file.replaceAll("<", "<").replaceAll(">", ">") + "</file>";
                str += "</xml>";
                output.writeUTF(str);
            }
            catch(Exception e1)
            {
                e1.printStackTrace();
            }
        }
    }
    public static void main(String args[])
    {
        new ClientWindow();
    }
    public void valueChanged(ListSelectionEvent e)
    {
        if(e.getSource() == ClientList && e.getValueIsAdjusting() == true)
        {
            SendTarget = ClientList.getSelectedValue()+"";
        }
    }
}
class GetPort
{
    int port = 0;
    GetPort()
    {
        for(int i = 3000;i < 9000;i++)
        {
            try
            {
                ServerSocket s = new ServerSocket(i);
                port = i;
                s.close();
                break;
            }
            catch(Exception e)
            {
                continue;
            }
        }
    }
}
class RecvThread extends Thread
{
    Socket serverSocket;
    JTextArea ShowText;
    DefaultListModel ClientListItems;
    RecvThread(Socket s,JTextArea j,DefaultListModel d)
    {
        serverSocket = s;
        ShowText = j;
        ClientListItems = d;
        start();
    }
    public void run()
    {
        while(true)
        {
            try
            {
                DataInputStream input = new DataInputStream(serverSocket.getInputStream());
                String recvstr = input.readUTF();
                String showtext = "";
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(new InputSource(new StringReader(recvstr)));
                Element root = doc.getDocumentElement();
                NodeList items = root.getChildNodes();
                String mark = items.item(0).getFirstChild().getNodeValue();
               
                if(mark.equals("1"))
                {
                    String sender = items.item(1).getFirstChild().getNodeValue();
                    String content = items.item(2).getFirstChild().getNodeValue();
                    showtext = sender + "说:" + content + "\n";
                }
                if(mark.equals("2"))
                {
                    ClientListItems.removeAllElements();
                    for(int i = 1;i < items.getLength();i++)
                    {
                        ClientListItems.addElement(items.item(i).getFirstChild().getNodeValue());
                    }
                }
                if(mark.equals("3"))
                {
                    String sender = items.item(1).getFirstChild().getNodeValue();
                    String content = items.item(2).getFirstChild().getNodeValue();
                    showtext = sender + "说:" + content + "\n";
                }
                if(mark.equals("4"))
                {
                    ClientListItems.removeAllElements();
                    for(int i = 1;i < items.getLength();i++)
                    {
                        ClientListItems.addElement(items.item(i).getFirstChild().getNodeValue());
                    }
                }
                if(mark.equals("5"))
                {
                    String sender = items.item(1).getFirstChild().getNodeValue();
                    String content = items.item(2).getFirstChild().getNodeValue();
                    showtext = sender + "说:" + content + "\n";
                }
                if(mark.equals("6"))
                {
                    String sender = items.item(1).getFirstChild().getNodeValue();
                    String content = items.item(2).getFirstChild().getNodeValue();
                    String target = items.item(3).getFirstChild().getNodeValue();
                    if(sender.equals("自己"))
                    {
                        showtext = sender + "悄悄对"+target+"说:" + content + "\n";
                    }
                    else
                    {
                        showtext = target + "悄悄对你说:" + content + "\n";
                    }
                }
                if(mark.equals("7"))
                {
                    String sender = items.item(1).getFirstChild().getNodeValue();
                    String ip = items.item(2).getFirstChild().getNodeValue();
                    String port = items.item(3).getFirstChild().getNodeValue();
                    String file = items.item(4).getFirstChild().getNodeValue();
                    
                    int result = JOptionPane.showConfirmDialog(null,sender+"想发送文件:"+file+"给你,是否接受?","",JOptionPane.YES_NO_CANCEL_OPTION);
                    if(result == JOptionPane.YES_OPTION)
                    {
                        try
                        {
                            FileDialog saveDialog = new FileDialog(new Frame(),"选择保存位置",FileDialog.SAVE);
                            saveDialog.setVisible(true);
                            if(saveDialog.getFile() != null)
                            {
                                if(!saveDialog.getFile().equals(""))
                                {
                                    Socket FileSocket = new Socket(ip,Integer.parseInt(port));
                                    new RecvFileThread(FileSocket,saveDialog.getDirectory() + saveDialog.getFile(),"begin");
                                }
                            }
                        }
                        catch(Exception e)
                        {
                            e.printStackTrace();
                        }
                    }
                    else
                    {
                        Socket FileSocket = new Socket(ip,Integer.parseInt(port));
                        new RecvFileThread(FileSocket,null,"end");
                    }
                    showtext = "";
                }
                ShowText.setText(ShowText.getText() + showtext.replaceAll("<", "<").replaceAll(">", ">"));
                ShowText.setCaretPosition(ShowText.getText().length());
            }
            catch (Exception e)
            {
                JOptionPane.showMessageDialog(null, "服务器已经退出");
                System.exit(0);
            }
        }
    }
}
class AcceptThread extends Thread
{
    String filepath;
    ServerSocket MySocket;
    int port;
    String ip;
    AcceptThread(String f)
    {
        try
        {
            filepath = f;
            port = new GetPort().port;
            MySocket = new ServerSocket(port);
            ip = InetAddress.getLocalHost().getHostAddress();
            start();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    public void run()
    {
        try
        {
            while(true)
            {
                Socket socket = MySocket.accept();
                DataInputStream input = new DataInputStream(socket.getInputStream());
                String recvstr = input.readUTF();
                if(recvstr.equals("begin"))
                {
                    try
                    {
                        ZipOutputStream out = new ZipOutputStream(socket.getOutputStream());
                        out.putNextEntry(new ZipEntry(filepath));
                        FileInputStream reader = new FileInputStream(filepath);
                        byte b[] = new byte[1024];
                        int n = -1;
                        while((n = reader.read(b, 0, 1024)) != -1)
                        {
                            out.write(b,0,n);
                        }
                        reader.close();
                        out.close();
                    }
                    catch(Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                if(recvstr.equals("end"))
                {
                    return;
                }
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}
class RecvFileThread extends Thread
{
    Socket FileSocket;
    String filepath;
    String mark;
    RecvFileThread(Socket s,String f,String m)
    {
        mark = m;
        filepath = f;
        FileSocket = s;
        start();
    }
    public void run()
    {
        try
        {
            if(mark.equals("end"))
            {
                DataOutputStream output1 = new DataOutputStream(FileSocket.getOutputStream());
                output1.writeUTF("end");
                return;
            }
            DataOutputStream output1 = new DataOutputStream(FileSocket.getOutputStream());
            output1.writeUTF("begin");
            
            File file = new File(filepath);
            FileOutputStream output = new FileOutputStream(file);
            
            byte b[] = new byte[1024];
            ZipInputStream in = new ZipInputStream(FileSocket.getInputStream());
            ZipEntry zipEntry = null;
            while(true)
            {
                if((zipEntry = in.getNextEntry()) != null)
                {
                    int n = -1;
                    while((n = in.read(b, 0, 1024)) != -1)
                    {
                        output.write(b, 0, n);
                    }
                }
                else
                {
                    break;
                }
                while((zipEntry = in.getNextEntry()) != null)
                {
                    int n = -1;
                    while((n = in.read(b, 0, 1024)) != -1)
                    {
                        String str = new String(b,0,n);
                        System.out.println(str);
                    }
                }
            }
            output.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}
回复

使用道具 举报

  • TA的每日心情
    开心
    2021-3-12 23:18
  • 签到天数: 2 天

    [LV.1]初来乍到

    发表于 2011-8-4 21:22:12 | 显示全部楼层
    谢谢楼主分享。
    回复 支持 反对

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-5-8 22:52 , Processed in 0.426813 second(s), 46 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表