码迷,mamicode.com
首页 > 其他好文 > 详细

socket

时间:2020-03-14 15:04:43      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:etl   print   init   int   dwr   round   lease   tput   except   

效果展示

技术图片

 

项目代码

客户端

public class Client extends JFrame implements Runnable {
    private static Socket socket;

    /**
     * 主方法
     *
     * @param args
     */
    public static void main(String[] args) {
        try {
            // 创建Socket对象,并绑定主机和端口
            socket = new Socket("127.0.0.1", 8888);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 判断连接是否建立
        if (socket.isConnected()) {
            new Thread(new Client(), "线程1").start();
        }
    }

    /**
     * 初始客户端
     */
    private void initClient() {
        Frame.getInstance().createFrame("Client");
        JButton send = Frame.getInstance().send;
        JButton cancel = Frame.getInstance().cancel;
        JTextArea msg = Frame.getInstance().msg;
        JTextArea record = Frame.getInstance().record;

        // 发送按钮点击事件监听
        send.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == 1 && !("").equals(msg.getText())) {
                    clientWrite(record, msg);
                }
            }
        });

        // 消息输入框键盘事件监听
        msg.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == 10) {
                    clientWrite(record, msg);
                }
            }
        });

        // 取消按钮点击事件监听
        cancel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == 1) {
                    msg.setText("");
                }
            }
        });

        // 读取
        try {
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String mess;
            while (null != (mess = br.readLine())) {
                if ("date".equals(mess)) {
                    record.append("服务端\t" + DateUtil.getInstance().getDate() + "\n");
                    continue;
                }
                record.append(mess + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入
     *
     * @param record
     * @param msg
     */
    private void clientWrite(JTextArea record, JTextArea msg) {
        try {
            record.append("客户端\t" + DateUtil.getInstance().getDate() + "\n");
            OutputStream os = socket.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
            record.append(msg.getText().trim() + "\n");
            bw.write("date\n" + msg.getText().trim() + "\n");
            bw.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void run() {
        initClient();
    }
}

 

服务端

public class Server {
    private static Socket socket;

    /**
     * 初始服务端
     */
    private void initServer() {
        try {
            // 创建ServerSocket对象,并绑定端口
            ServerSocket serverSocket = new ServerSocket(8888);
            // 连接监听
            socket = serverSocket.accept();
            // 判断连接是否建立
            if (socket.isConnected()) {
                Frame.getInstance().createFrame("Server");
                JButton send = Frame.getInstance().send;
                JButton cancel = Frame.getInstance().cancel;
                JTextArea msg = Frame.getInstance().msg;
                JTextArea record = Frame.getInstance().record;

                // 发送按钮点击事件监听
                send.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        if (e.getButton() == 1 && !("").equals(msg.getText())) {
                            serverWrite(record, msg);
                        }
                    }
                });

                // 消息输入框键盘事件监听
                msg.addKeyListener(new KeyAdapter() {
                    @Override
                    public void keyReleased(KeyEvent e) {
                        if (e.getKeyCode() == 10) {
                            serverWrite(record, msg);
                        }
                    }
                });

                // 取消按钮点击事件监听
                cancel.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        if (e.getButton() == 1) {
                            msg.setText("");
                        }
                    }
                });

                // 读取
                try {
                    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    String mess;
                    while (null != (mess = br.readLine())) {
                        if ("date".equals(mess)) {
                            record.append("客户端\t" + DateUtil.getInstance().getDate() + "\n");
                            continue;
                        }
                        record.append(mess + "\n");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入
     *
     * @param record
     * @param msg
     */
    private void serverWrite(JTextArea record, JTextArea msg) {
        try {
            record.append("服务端\t" + DateUtil.getInstance().getDate() + "\n");
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            record.append(msg.getText().trim() + "\n");
            bw.write("date\n" + msg.getText().trim() + "\n");
            bw.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 主方法
     *
     * @param args
     */
    public static void main(String[] args) {
        new Server().initServer();
    }
}

 

GUI

class Frame extends JFrame {
    private static Frame frame;
    JTextArea record;
    JTextArea msg;
    JButton send;
    JButton cancel;

    /**
     * 构造
     */
    private Frame() {
    }

    /**
     * 获取实例
     *
     * @return
     */
    static Frame getInstance() {
        if (frame == null) {
            frame = new Frame();
        }
        return frame;
    }

    /**
     * 创建窗体
     *
     * @param frameTitle
     */
    void createFrame(String frameTitle) {
        // 窗体
        this.setSize(1200, 900);
        this.setTitle(frameTitle);
        this.setLocationRelativeTo(null);
        this.setResizable(false);

        // 容器
        JPanel panel = new JPanel(null);

        // 聊天记录
        record = new JTextArea();
        record.setBounds(0, 0, 1200, 600);
        record.setFont(new Font("宋体", Font.PLAIN, 22));
        record.setOpaque(true);
        record.setBackground(Color.lightGray);
        record.setEditable(false);
        JScrollPane recordScrollPane = new JScrollPane(record);
        recordScrollPane.setBounds(0, 0, 1200, 600);
        panel.add(recordScrollPane);

        // 消息
        msg = new JTextArea();
        msg.setBounds(0, 600, 1200, 200);
        msg.setFont(new Font("宋体", Font.PLAIN, 22));
        JScrollPane msgScrollPane = new JScrollPane(msg);
        msgScrollPane.setBounds(0, 600, 1200, 200);
        panel.add(msgScrollPane);

        // 发送
        send = new JButton("Send");
        send.setBounds(970, 810, 100, 50);
        send.setFont(new Font("宋体", Font.PLAIN, 22));
        panel.add(send);

        // 取消
        cancel = new JButton("Cancel");
        cancel.setBounds(1090, 810, 100, 50);
        cancel.setFont(new Font("宋体", Font.PLAIN, 22));
        panel.add(cancel);

        // 显示窗体
        this.add(panel);
        this.setVisible(true);
    }
}

 

时间处理方法

    String getDate() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

 

socket

标签:etl   print   init   int   dwr   round   lease   tput   except   

原文地址:https://www.cnblogs.com/lightbc/p/12491862.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!