javase基础socket编程之局域网聊天,局域网文件共享

来源:互联网 发布:高斯分布 python 编辑:程序博客网 时间:2024/05/21 06:47

javase基础学完可以做什么,javase实现局域网聊天室

包含内容:基础语法,面向对象,多线程,IO流,GUI编程,网络编程(udp)

实现功能:局域网群聊,局域网群发文件(还不太完善,只能传输小体积的文本文件)

由于本人也是刚开始学java,而且掌握的不太好,所以代码可能有些臃肿。请谅解

登录界面


主界面


package test;//包名自己改下//新手上路代码比较臃肿,请谅解,直接拷贝即可运行import java.awt.*;import java.awt.event.*;import java.io.*;import java.net.*;import javax.swing.*;import javax.swing.filechooser.*;public class Chatdemo2{    private static JFrame loginjf;    public static void main(String[] args)    {        loginView();    }    private static void loginView()    {        loginjf = new JFrame("输入自己的名字");        final JTextField nametext = new JTextField(10);        loginjf.setLayout(new FlowLayout());        JButton jb = new JButton("登录");        loginjf.add(nametext);        loginjf.add(jb);        nametext.addActionListener(new ActionListener()        {            public void actionPerformed(ActionEvent e)            {                if(nametext.getText().equals(""))                {                    JDialog jdl=new JDialog(loginjf,"提示",true);                    jdl.setBounds(500, 200, 400, 150);                    jdl.setLayout(new FlowLayout());                    JLabel jl1=new JLabel("用户名不能为空");                    jdl.add(jl1);                    jdl.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);                    jdl.setVisible(true);                }else {                    String name = nametext.getText();                    loginjf.dispose();                    new MainFrame(name);                }            }        });        jb.addActionListener(new ActionListener()        {            public void actionPerformed(ActionEvent e)            {                if(nametext.getText().equals(""))                {                    JDialog jdl=new JDialog(loginjf,"提示",true);                    jdl.setBounds(500, 200, 400, 150);                    jdl.setLayout(new FlowLayout());                    JLabel jl1=new JLabel("用户名不能为空");                    jdl.add(jl1);                    jdl.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);                    jdl.setVisible(true);                }else {                    String name = nametext.getText();                    loginjf.dispose();                    new MainFrame(name);                }            }        });        loginjf.setBounds(450, 300, 350, 100);        loginjf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);        loginjf.setVisible(true);    }}class MainFrame{    private final String name;    private DatagramSocket sendSocket;    private DatagramSocket receSocket;    private DatagramSocket fileReceSocket;    private JTextArea jta;    private JTextField jtf;    private String localip;    private JFrame jFrame;    private File file;    private String datass;    public MainFrame(String s)    {        this.name = s;        initView();        new Thread()        {            public void run()            {                mygetmsg();            }        }.start();        new Thread()        {            public void run()            {                mygetfile();            }        }.start();    }    private void initView()    {        try        {            sendSocket = new DatagramSocket(10002);            receSocket = new DatagramSocket(10003);            fileReceSocket = new DatagramSocket(10004);                        localip = InetAddress.getLocalHost().getHostAddress();            System.out.println(localip);            String[] strings = localip.split("\\.");            String radioip = strings[0] + "." + strings[1] + ".255"+ ".255";            System.out.println(radioip);                        jFrame = new JFrame("局域网聊天室1.0");            jFrame.setBounds(450, 80, 500, 600);            jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);            JMenuBar jmb = new JMenuBar();            JMenu jm = new JMenu("文件");            JMenu jm1=new JMenu("学习");            JMenu jm2=new JMenu("关于");            JMenuItem jmi1 = new JMenuItem("群发文件");            JMenuItem jmi2 = new JMenuItem("群发文件说明");            JMenuItem jmi3 = new JMenuItem("我要自学java");            JMenuItem jmi4 = new JMenuItem("百度一下");            JMenuItem jmi5 = new JMenuItem("关于作者");            jmb.add(jm);            jmb.add(jm1);            jmb.add(jm2);                        jm.add(jmi1);            jm.add(jmi2);            jm1.add(jmi3);            jm1.add(jmi4);            jm2.add(jmi5);            jFrame.setJMenuBar(jmb);            jta = new JTextArea();            JScrollPane jsp = new JScrollPane(jta);            jtf = new JTextField(10);            jta.setEditable(false);            jFrame.add(jsp, BorderLayout.CENTER);            jFrame.add(jtf, BorderLayout.SOUTH);            jFrame.setVisible(true);                        String loginOk = "【"+ name +"】上线了" + "                      (*^__^*)系统提示(*^__^*)";            byte[] b = loginOk.getBytes();            DatagramPacket loginpack = new DatagramPacket(b, b.length,InetAddress.getByName("255.255.255.255"), 10003);            sendSocket.send(loginpack);                        jmi1.addActionListener(new FileListen(sendSocket,jFrame,name));            jmi2.addActionListener(new ActionListener()            {                public void actionPerformed(ActionEvent e)                {                    JDialog jdl=new JDialog(jFrame,"提示",true);                    jdl.setBounds(500, 200, 400, 150);                    jdl.setLayout(new FlowLayout());                    JLabel jl1=new JLabel("注意:本程序为UDP传输实现,可能会丢失数据!~~~~(>_<)~~~~");                    JLabel jl2=new JLabel("       所以群发文件时候只能群发文本文档! ~~~~(>_<)~~~~");                    JLabel jl3=new JLabel("       其他文件发送出去可能会成乱码文件! ~~~~(>_<)~~~~");                    jdl.add(jl1);                    jdl.add(jl2);                    jdl.add(jl3);                    jdl.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);                    jdl.setVisible(true);                }});            jmi3.addActionListener(new ActionListener()            {                public void actionPerformed(ActionEvent e)                {                    JDialog jdl=new JDialog(jFrame,"O(∩_∩)O",true);                    jdl.setBounds(600, 200, 170, 150);                    jdl.setLayout(new FlowLayout());                    JLabel jl1=new JLabel("百度是最好的老师!");                    JLabel jl2=new JLabel("快点开百度学习吧!");                    JLabel jl3=new JLabel(" O(∩_∩)O哈哈~ ");                    jdl.add(jl1);                    jdl.add(jl2);                    jdl.add(jl3);                    jdl.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);                    jdl.setVisible(true);                }});            jmi4.addActionListener(new ActionListener()            {                public void actionPerformed(ActionEvent e)                {                    try                    {                        Runtime.getRuntime().exec("explorer http://www.baidu.com");                    } catch (Exception e1)                    {                        e1.printStackTrace();                    }                }});            jmi5.addActionListener(new ActionListener()            {                public void actionPerformed(ActionEvent e)                {                    JDialog jdl=new JDialog(jFrame,"(*^__^*)",true);                    jdl.setBounds(600, 200, 170, 150);                    jdl.setLayout(new FlowLayout());                    JLabel jl1=new JLabel("QQ:       835476090");                    JLabel jl2=new JLabel("Designer:  a * 大火");                    JLabel jl3=new JLabel("teacher:    张大鹏");                    jdl.add(jl1);                    jdl.add(jl2);                    jdl.add(jl3);                    jdl.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);                    jdl.setVisible(true);                }});            jtf.addActionListener(new MsgListen(sendSocket,jtf,name));            jFrame.addWindowListener(new WindowClose(sendSocket,name));        } catch (Exception e)        {            e.printStackTrace();        }    }    private void mygetmsg()    {        try        {            while (true)            {                byte[] buf = new byte[1024];                DatagramPacket dp = new DatagramPacket(buf, buf.length);                receSocket.receive(dp);                String data = new String(dp.getData(), 0, dp.getLength());                                jta.append(data + "\r\n");            }        } catch (Exception e)        {            e.printStackTrace();        }    }    private void mygetfile()    {        FileSystemView fsv = FileSystemView.getFileSystemView();        File com = fsv.getHomeDirectory();        String deskpath = com.getPath();        try        {            while (true)            {                        byte[] buf = new byte[1024*1024];                DatagramPacket dp = new DatagramPacket(buf, buf.length);                fileReceSocket.receive(dp);                        String senderip=dp.getAddress().getHostAddress();                String data = new String(dp.getData(), 0, dp.getLength());                String datacopy=data;                data = data.replace("铮标记", "");                File filedir=new File(deskpath+"/"+senderip);                file= new File(filedir,data);                    if (datacopy.contains("大火标记"))                {                    datass=data;                    System.out.println(datass);                    if (!filedir.exists())                    {                        System.out.println(filedir.mkdirs());                    }                    if (!file.exists())                    {                        System.out.println(file.createNewFile());                    }                }else                {                    file= new File(filedir,datass);                    FileOutputStream fos=new FileOutputStream(file);                    fos.write(data.getBytes());                    fos.close();                    /*也可以                    RandomAccessFile raf = new RandomAccessFile(file, "rw");                    raf.seek(0);                    for (int b = 0; b < i; b++)                    {                        raf.readLine();                    }                    raf.write(data.getBytes());                    raf.close();                    i++;*/                }            }        } catch (Exception e)        {            e.printStackTrace();        }    }}class MsgListen implements ActionListener{    private DatagramSocket sendSocket;    private JTextField jtf;    private String name;    public MsgListen(DatagramSocket sendSocket,JTextField jtf,String name)    {        this.sendSocket=sendSocket;        this.jtf=jtf;        this.name=name;    }    public void actionPerformed(ActionEvent e)    {        String string = jtf.getText();        jtf.setText("");        String string1=name+":"+string;        byte[] buf = string1.getBytes();        try        {            DatagramPacket data = new DatagramPacket(buf,                    buf.length, InetAddress                            .getByName("255.255.255.255"), 10003);            sendSocket.send(data);        } catch (Exception e1)        {            e1.printStackTrace();        }    }}class FileListen implements ActionListener{    private DatagramSocket sendSocket;        private JFrame jFrame;    private String name;    public FileListen(DatagramSocket sendSocket,JFrame jFrame,String name)    {        this.sendSocket=sendSocket;        this.jFrame=jFrame;        this.name=name;    }    public void actionPerformed(ActionEvent e)    {        try        {            FileDialog fileDialog = new FileDialog(jFrame, "对话框"); // 菜单项被选中时就打开一个对话框,让用户选择一个文件            fileDialog.setVisible(true); // 对话框显示出来            if (fileDialog.getFile() != null                    && fileDialog.getDirectory() != null)            {                String fname = fileDialog.getFile();                String url = fileDialog.getDirectory();                String urlname = url + fname;                File file1 = new File(urlname);                String filename1=fname+"大火标记";                byte[] filename = filename1.getBytes();                DatagramPacket filenamepack = new DatagramPacket(filename, filename.length, InetAddress.getByName("255.255.255.255"), 10004);                sendSocket.send(filenamepack);                FileInputStream fr=new FileInputStream(file1);                byte[] buf= new byte[1024*500];                int len;                while ((len = fr.read(buf)) != -1)                {                    DatagramPacket filedatapack = new DatagramPacket(buf,len, InetAddress.getByName("255.255.255.255"), 10004);                    sendSocket.send(filedatapack);                }                fr.close();                String sendOk = "【"+ name +"】给大家发了个文件,你们看下收到没" + "       (*^__^*)系统提示(*^__^*)";                byte[] b = sendOk.getBytes();                DatagramPacket senOkpack = new DatagramPacket(b, b.length,InetAddress.getByName("255.255.255.255"), 10003);                sendSocket.send(senOkpack);            }        } catch (Exception e1)        {            e1.printStackTrace();        }    }}class WindowClose extends WindowAdapter{    private DatagramSocket sendSocket;        private String name;    public WindowClose(DatagramSocket sendSocket,String name)    {        this.sendSocket=sendSocket;        this.name=name;    }    public void windowClosing(WindowEvent e)    {        try        {            String offline = "【"+ name +"】下线了" + "                      (*^__^*)系统提示(*^__^*)";            byte[] b = offline.getBytes();            DatagramPacket offlinepack = new DatagramPacket(b, b.length,InetAddress.getByName("255.255.255.255"), 10003);            sendSocket.send(offlinepack);        } catch (Exception e1)        {            e1.printStackTrace();        }    }}