前一段时间和几个好友组队参加了中兴举办的“中兴捧月杯”程序设计大赛,跌跌撞撞竟然进了复赛,不过最终还是没能入围区域决赛,还是感觉很遗憾。这里把当时复赛的题目以及我们被Out的代码拿来晒晒,也算记录下我们曾经参加过此次活动哈。复赛题目的意思很简单,就是要求做一个报文监视器的客户端,用于接收服务器发来的各种信息并与之交流,要求能够实现多线程、界面良好、各客户端之间能够实现对等方式的交互、按一定格式输出服务器发来的信息,一个服务器可以连上若干个客户端。下面是我们的代码:

//客户端线程类
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.net.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.StringTokenizer;

class ClientFrameThread extends Thread {

JFrame frame = new JFrame();
    private int count = 0;
    private final int WIDTH = 700;
    private final int HEIGHT = 500;
    private Container content = frame.getContentPane();
    private JPanel inputPane = new JPanel();
    private JLabel ip = new JLabel("服务器地址");
    private JTextField ip_input = new JTextField(30);
    private JLabel port = new JLabel("服务端口号");
    private JTextField port_input = new JTextField(30);
    private JButton ok = new JButton("连接");
    private JButton cancle = new JButton("重置");
    private JButton close = new JButton("关闭");
    private JButton b_legalMessage = new JButton("合法报文");
    private JButton b_illegalMessage = new JButton("非法报文");
    private JLabel filterKeyWords = new JLabel("过滤关键字");
    private JTextField filterKeyWordsInput = new JTextField(30);
    private JLabel maxMessageNum = new JLabel("最大报文数");
    private JTextField maxMessageNumInput = new JTextField(30);
    private JTextArea legalMessage = new JTextArea(15, 50);
    private JTextArea illegalMessage = new JTextArea(15, 50);
    private JPanel p = new JPanel();
    private Socket client = null;
    private BufferedReader is = null;
    private JScrollPane legalMessagePane = new JScrollPane(legalMessage, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    private JScrollPane illegalMessagePane = new JScrollPane(illegalMessage, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    private CardLayout card = new CardLayout();
    private ArrayList tempFileString = new ArrayList();

public void add(Component c, GridBagConstraints constraints, int x, int y, int w, int h) {
        constraints.gridx = x;
        constraints.gridy = y;
        constraints.gridwidth = w;
        constraints.gridheight = h;
        frame.add(c, constraints);
    }

public ClientFrameThread(String name) {
        this.setName(name);
        content.setBackground(Color.CYAN);
        frame.setTitle(this.getName());
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension screenSize = kit.getScreenSize();
        int w = screenSize.width;
        int h = screenSize.height;
        int x = (w - WIDTH) / 2;
        int y = (h - HEIGHT) / 2;
        frame.setLocation(x, y);
        frame.setSize(WIDTH, HEIGHT);

GridBagLayout lay = new GridBagLayout();
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.weightx = 5;
        constraints.weighty = 20;
        constraints.fill = GridBagConstraints.NONE;
        frame.setLayout(lay);
        add(ip, constraints, 0, 0, 1, 1);
        add(ip_input, constraints, 1, 0, 4, 1);
        add(port, constraints, 0, 1, 1, 1);
        add(port_input, constraints, 1, 1, 4, 1);
        add(filterKeyWords, constraints, 0, 2, 1, 1);
        add(filterKeyWordsInput, constraints, 1, 2, 4, 1);
        add(maxMessageNum, constraints, 0, 3, 1, 1);
        add(maxMessageNumInput, constraints, 1, 3, 4, 1);
        add(ok, constraints, 0, 4, 1, 1);
        ok.addActionListener(new ConnectListener());
        add(cancle, constraints, 1, 4, 1, 1);
        cancle.addActionListener(new CancleListener());
        add(close, constraints, 2, 4, 1, 1);
        close.addActionListener(new CloseListener());
        add(b_legalMessage, constraints, 3, 4, 1, 1);
        b_legalMessage.addActionListener(new messageListener());
        add(b_illegalMessage, constraints, 4, 4, 1, 1);
        b_illegalMessage.addActionListener(new messageListener());
        legalMessage.setBackground(Color.YELLOW);
        illegalMessage.setBackground(Color.GREEN);

p.setLayout(card);
        p.add("legalMessage", legalMessagePane);

p.add("illegalMessage", illegalMessagePane);
        add(p, constraints, 0, 5, 5, 15);
        frame.setVisible(true);
    }

class myThread extends Thread {

public void run() {
            int maxNum = Integer.MAX_VALUE;
            if (!maxMessageNumInput.getText().isEmpty()) {
                try {
                    maxNum = Integer.parseInt(maxMessageNumInput.getText());
                } catch (Exception ee) {
                    maxNum = Integer.MAX_VALUE;
                }
            }
            String ipText = ip_input.getText();
            String key = filterKeyWordsInput.getText();
            int portNum = Integer.parseInt(port_input.getText());
            try {

client = new Socket(ipText, portNum);
                is = new BufferedReader(new InputStreamReader(client.getInputStream()));
                StringBuffer toPrint = new StringBuffer();
                int COUNT = 0;
                while (COUNT < Integer.MAX_VALUE) {
                    String Msg = is.readLine();
                    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy     HH:mm:ss ");
                    String date = sdf.format(new Date());

String year = date.substring(8, 10);
                    String month = date.substring(0, 2);
                    String day = date.substring(3, 5);
                    String time = date.substring(14, 23);
                    toPrint.append("[");
                    toPrint.append(year);
                    toPrint.append("/");
                    toPrint.append(month);
                    toPrint.append("/");
                    toPrint.append(day);
                    toPrint.append(" ");
                    toPrint.append(time);
                    toPrint.append("]");
                    toPrint.append(" ");
                    toPrint.append(Msg);
                    System.out.println(toPrint);
                    if (!StringCut(Msg, key)) {
                        illegalMessage.append(toPrint.toString() + '\n');
                        tempFileString.add(count % maxNum, toPrint.toString());
                        if (count >= maxNum) {
                            tempFileString.remove(count % maxNum + 1);
                        }
                        count++;
                        toPrint.delete(0, toPrint.capacity());
                        continue;
                    } else {
                        legalMessage.append(toPrint.toString() + '\n');
                        tempFileString.add(count % maxNum, toPrint.toString());
                        if (count >= maxNum) {
                            tempFileString.remove(count % maxNum + 1);
                        }
                        count++;
                        toPrint.delete(0, toPrint.capacity());
                    }
                    COUNT++;

}

is.close();
                client.close();

} catch (Exception ex) {
                System.out.println("Cannot connect to server!!!");
                ex.printStackTrace();
            }

}
    }

class messageListener implements ActionListener {

public void actionPerformed(ActionEvent e) {
            if (e.getSource() == b_legalMessage) {
                card.show(p, "legalMessage");
            } else if (e.getSource() == b_illegalMessage) {
                card.show(p, "illegalMessage");
            }
        }
    }

class ConnectListener implements ActionListener {

public void actionPerformed(ActionEvent e) {
            try {
                if (ip_input.getText().isEmpty() || port_input.getText().isEmpty()) {
                    JOptionPane.showMessageDialog(null, "请输入Server的IP和port!!");
                }
                String key = "";
                if (!filterKeyWordsInput.getText().isEmpty()) {
                    key = filterKeyWordsInput.getText();
                }
                if (isLegalKey(key)) {
                    new myThread().start();
                } else {
                    JOptionPane.showMessageDialog(null, "你输入的过滤关键字不合法,请确认!提示:错误可能是缺少括号或者单词错误!!");
                }
            } catch (Exception ee) {
                ee.printStackTrace();
            }
        }
    }

public static boolean StringCut(String source, String key) {
        StringTokenizer st = new StringTokenizer(key);
        int size = st.countTokens();
        //单个关键字
        if (size == 1) {
            if (source.indexOf(key) >= 0) {
                return false;
            }
        } //两个关键字
        else if (size == 3 && !(key.indexOf("(") >= 0)) {
            String temp[] = new String[3];
            int count = 0;
            while (st.hasMoreElements()) {
                String t = st.nextToken();
                temp[count] = t;
                count++;
            }
            if (temp[1].equals("and")) {
                if (source.indexOf(temp[0].substring(1, temp[0].length() - 1)) >= 0
                        && source.indexOf(temp[2].substring(1, temp[2].length() - 1)) >= 0) {
                    return false;
                }
            } else if (temp[1].equals("or")) {
                if (source.indexOf(temp[0].substring(1, temp[0].length() - 1)) >= 0
                        || source.indexOf(temp[2].substring(1, temp[2].length() - 1)) >= 0) {
                    return false;
                }
            }
        } //三个关键字不带括号
        else if (size == 5 && !(key.indexOf("(") >= 0) && !(key.indexOf(")") >= 0)) {
            String temp[] = new String[5];
            int count = 0;
            while (st.hasMoreElements()) {
                String t = st.nextToken();
                temp[count] = t;
                count++;
            }
            if (temp[1].equals("or") && temp[3].equals("or")) {
                if (source.indexOf(temp[0].substring(1, temp[0].length() - 1)) >= 0
                        || source.indexOf(temp[2].substring(1, temp[2].length() - 1)) >= 0
                        || source.indexOf(temp[4].substring(1, temp[4].length() - 1)) >= 0) {
                    return false;
                }
            } else if (temp[1].equals("and") && temp[3].equals("and")) {
                if (source.indexOf(temp[0].substring(1, temp[0].length() - 1)) >= 0
                        && source.indexOf(temp[2].substring(1, temp[2].length() - 1)) >= 0
                        && source.indexOf(temp[4].substring(1, temp[4].length() - 1)) >= 0) {
                    return false;
                }
            } else if (temp[1].equals("and") && temp[3].equals("or")) {
                if (source.indexOf(temp[0].substring(1, temp[0].length() - 1)) >= 0
                        && source.indexOf(temp[2].substring(1, temp[2].length() - 1)) >= 0
                        || source.indexOf(temp[4].substring(1, temp[4].length() - 1)) >= 0) {
                    return false;
                }
            } else if (temp[1].equals("or") && temp[3].equals("and")) {
                if (source.indexOf(temp[2].substring(1, temp[2].length() - 1)) >= 0
                        && source.indexOf(temp[4].substring(1, temp[4].length() - 1)) >= 0
                        || source.indexOf(temp[0].substring(1, temp[0].length() - 1)) >= 0) {
                    return false;
                }
            }
            //三个关键字带括号
        } else if (size == 5 && (key.indexOf("(") >= 0) && (key.indexOf(")") >= 0)) {
            int indexLeft = key.indexOf("(");
            int indexRight = key.indexOf(")");
            System.out.println(indexLeft + "  " + indexRight + "  " + key.length());
            String temp[] = new String[5];
            int count = 0;
            while (st.hasMoreElements()) {
                String t = st.nextToken();
                temp[count] = t;
                count++;
            }
            if (indexRight == key.length() - 1) {
                String left = temp[2].substring(2, temp[2].length() - 1);
                String right = temp[4].substring(1, temp[4].length() - 2);
                String first = temp[0].substring(1, temp[0].length() - 1);
                if (temp[1].equals("and") && temp[3].equals("and")) {
                    if (source.indexOf(left) >= 0 && source.indexOf(right) >= 0 && source.indexOf(first) >= 0) {
                        return false;
                    }
                } else if (temp[1].equals("or") && temp[3].equals("or")) {
                    if (source.indexOf(left) >= 0 || source.indexOf(right) >= 0 || source.indexOf(first) >= 0) {
                        return false;
                    }
                } else if (temp[1].equals("and") && temp[3].equals("or")) {
                    if ((source.indexOf(left) >= 0 || source.indexOf(right) >= 0) && source.indexOf(first) >= 0) {
                        return false;
                    }
                } else if (temp[1].equals("or") && temp[3].equals("and")) {
                    if ((source.indexOf(left) >= 0 && source.indexOf(right) >= 0) || source.indexOf(first) >= 0) {
                        return false;
                    }
                }
            } else {
                String left = temp[0].substring(2, temp[2].length() - 1);
                String right = temp[2].substring(1, temp[4].length() - 2);
                String first = temp[4].substring(1, temp[0].length() - 1);
                if (temp[1].equals("and") && temp[3].equals("and")) {
                    if (source.indexOf(left) >= 0 && source.indexOf(right) >= 0 && source.indexOf(first) >= 0) {
                        return false;
                    }
                } else if (temp[1].equals("or") && temp[3].equals("or")) {
                    if (source.indexOf(left) >= 0 || source.indexOf(right) >= 0 || source.indexOf(first) >= 0) {
                        return false;
                    }
                } else if (temp[1].equals("and") && temp[3].equals("or")) {
                    if ((source.indexOf(left) >= 0 && source.indexOf(right) >= 0) || source.indexOf(first) >= 0) {
                        return false;
                    }
                } else if (temp[1].equals("or") && temp[3].equals("and")) {
                    if ((source.indexOf(left) >= 0 || source.indexOf(right) >= 0) && source.indexOf(first) >= 0) {
                        return false;
                    }
                }
            }
        }

return true;
    }

public boolean isLegalKey(String key) {
        StringTokenizer st = new StringTokenizer(key);
        int size = st.countTokens();
        if (size == 3) {
            String temp[] = new String[3];
            int count = 0;
            while (st.hasMoreElements()) {
                String t = st.nextToken();
                temp[count] = t;
                count++;
            }
            if (!temp[1].equals("and") && !temp[1].equals("or")) {
                return false;
            }
        } else if (size == 5) {
            String temp[] = new String[5];
            int count = 0;
            while (st.hasMoreElements()) {
                String t = st.nextToken();
                temp[count] = t;
                count++;
            }
            if (!temp[1].equals("and") && !temp[1].equals("or")) {
                return false;
            }
            if (!temp[3].equals("and") && !temp[3].equals("or")) {
                return false;
            }
            if (key.indexOf("(") >= 0 && !(key.indexOf(")") >= 0)) {
                return false;
            }
            if (key.indexOf(")") >= 0 && !(key.indexOf("(") >= 0)) {
                return false;
            }
        }
        return true;
    }

class CancleListener implements ActionListener {

public void actionPerformed(ActionEvent e) {
            ip_input.setText("");
            port_input.setText("");
        }
    }

class CloseListener implements ActionListener {

public void actionPerformed(ActionEvent e) {
            try {
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd/HH:mm:ss");
                String date1 = sdf1.format(new Date());
                String yearString = date1.substring(0, 4);
                String monthString = date1.substring(5, 7);
                String dayString = date1.substring(8, 10);
                String hourString = date1.substring(11, 13);
                String minuteString = date1.substring(14, 16);
                String secondString = date1.substring(17, date1.length());
                String time1 = yearString + monthString + dayString + hourString + minuteString + secondString;
                String saveName = time1 + ".txt";
                File saveFile = new File(saveName);
                PrintWriter pw = new PrintWriter(new FileOutputStream(saveFile));
                for (Iterator it = tempFileString.iterator(); it.hasNext();) {
                    String temp = (String) it.next();
                    pw.println(temp);
                }
                pw.flush();
                pw.close();
            } catch (Exception ee) {
                ee.printStackTrace();
            }
            frame.dispose();
        }
    }

public void run() {
    }
}
//主函数部分

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Administrator
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ClientMain extends JFrame {

private Container content;
    private JLabel threadNum;
    private JTextField threadNumInput = new JTextField(10);
    private JButton ok;
    private JButton cancel;
    private JLabel title;
    private final int WIDTH = 400;
    private final int HEIGHT = 200;

public void add(Component c, GridBagConstraints constraints, int x, int y, int w, int h) {
        constraints.gridx = x;
        constraints.gridy = y;
        constraints.gridwidth = w;
        constraints.gridheight = h;
        add(c, constraints);
    }

public ClientMain() {
        content = this.getContentPane();
        content.setBackground(Color.YELLOW);
        Font f = new Font("宋体", Font.PLAIN, 14);
        this.setTitle("KingIV报文监视器");
        threadNum = new JLabel("监听电信设备数目:");
        threadNum.setFont(f);
        ok = new JButton("确定");
        ok.setFont(f);
        cancel = new JButton("重置");
        cancel.setFont(f);
        title = new JLabel("欢迎使用KingIV报文监视器");
        title.setFont(f);
        GridBagLayout lay = new GridBagLayout();
        content.setLayout(lay);
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.weightx = 4;
        constraints.weighty = 3;
        constraints.fill = GridBagConstraints.NONE;
        add(title, constraints, 1, 0, 2, 1);
        add(threadNum, constraints, 0, 1, 2, 1);
        add(threadNumInput, constraints, 2, 1, 2, 1);
        add(ok, constraints, 1, 2, 1, 1);
        ok.addActionListener(new OkListener());
        add(cancel, constraints, 2, 2, 1, 1);
        cancel.addActionListener(new CancelListener());
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension screenSize = kit.getScreenSize();
        int w = screenSize.width;
        int h = screenSize.height;
        int x = (w - WIDTH) / 2;
        int y = (h - HEIGHT) / 2;
        this.setLocation(x, y);
        this.setSize(WIDTH, HEIGHT);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }

class OkListener implements ActionListener {

public void actionPerformed(ActionEvent e) {
            if (threadNumInput.getText().isEmpty()) {
                JOptionPane.showMessageDialog(null, "请输入所要监听的电信设备数目!!");
            } else {
                dispose();
                int num = Integer.parseInt(threadNumInput.getText());
                ClientFrameThread[] client = new ClientFrameThread[num];
                for (int i = 0; i < num; i++) {
                    client[i] = new ClientFrameThread("KingIV报文监听器" + String.valueOf(i + 1));
                }

for (int j = 0; j < num; j++) {
                    client[j].start();
                }
            }
        }
    }

class CancelListener implements ActionListener {

public void actionPerformed(ActionEvent e) {
            threadNumInput.setText("");
        }
    }

public static void main(String[] args) {
        new ClientMain();
    }
}

转载于:https://blog.51cto.com/wwssttt/382406

“中兴捧月”报文监视器的实现相关推荐

  1. Deepsort_V2 2020中兴捧月阿尔法赛道多目标检测和跟踪初赛第一名

    2020中兴捧月阿尔法赛道多目标检测和跟踪初赛第一名方案 初赛:多目标跟踪:指标MOTA和MOTP, 后期的大量实验证明检测算法相对于跟踪更重要. 数据集分析: 1.人群密集稀疏场景: 2.场景(白天 ...

  2. 谈谈中兴捧月大赛决赛以及总结

    前言 四月份,在师兄的推荐下,报名参加了中兴捧月大赛.一开始只是为了混一个面笔试的资格(因为提交有效成绩即可免笔试),然后为了找一个简单的赛道,注册了几个号看了两三个赛道的题目.发现自己每个都不熟悉, ...

  3. 中兴捧月大赛之方案探讨

    昨天参加完中兴捧月的决赛,感觉特别的糟糕.说实话,感觉中兴这次比赛搞得真的很奇葩!一是比赛搞得让我觉得公司对整个比赛的态度有点随意,有点不正式.二是比赛的赛题要求每天都在变,感觉不天天关注活动交流区, ...

  4. 2023第十三届“中兴捧月”全球精英挑战赛今日正式启动

    3月31日,第十三届"中兴捧月"全球精英挑战赛正式启动! 由中兴通讯主办的"中兴捧月"大赛,自2009年首次举办至今,已走过13个年头,是广大高校师生的重点关注 ...

  5. 2020年中兴捧月算法大赛---埃德加考特派赛题解析及代码

    写在前面 三月份疫情期间在家闲来无事, 各大公司举办了很多的算法比赛, 但是大多是人工智能相关, 而我这个菜鸡又不会这方面的, 这时发现了中兴捧月的埃德加考特派赛道, 也就是数据库相关本科课设, 恰好 ...

  6. 2020中兴捧月算法大赛-阿尔法(MOT)赛道--赛后总结

    比赛结束了,很荣幸拿到了中兴捧月算法大赛 MOT赛道 全国总决赛第二名的亚军奖杯,这估计也是我找到工作前最后一个比赛了,收获满满,下面算是自己给自己写的一个简单的赛后总结,做的比较粗糙,细节也就不多赘 ...

  7. 2020中兴捧月算法赛道傅里叶派赛题菜鸡回顾

    最近抱着试水的心理参加了2020中兴捧月算法大赛傅里叶派赛题.从4.19号由旁观者转变为参赛者,到5.8号提交完成最后的文档和代码,前后算起来也有20天了.虽然自己比较菜,但毕竟是第一次参加这种比较正 ...

  8. 2019中兴捧月算法大赛历程

    1.初赛 题目是网络流量均衡.再带宽限制的图中求不同请求带宽的各条业务的最短路径使总成本最小. 解题思路: 对业务进行排序,优先级高的业务去走热点链路,优先级低的业务发现热点链路已经达到带宽上限就绕路 ...

  9. 2020中兴捧月算法精英挑战赛-迪杰斯特拉派初赛(未来城市物流系统)总结

    疫情关系,导致科研一直没法开展,老板着急,自己也无所事事.在清明过后看到了中兴的算法精英挑战赛,然后就开始了算法之旅,这里自己做一点总结,为自己以后争取点教训吧. 数据分析的重要性 这次比赛真的让我体 ...

最新文章

  1. 导入eclipse项目运行时run as no application
  2. 数据治理(Data Governance)
  3. POSTMAN 数据关联
  4. 需求用例分析之一:异常流
  5. payment on barclays
  6. getAttribute与getParameter的区别
  7. 教你如何使用hexo以及nginx、github搭建属于自己的博客(操心的妈妈级教学)
  8. Linux虚拟机重启后无法获取IP的问题(断网、没网)
  9. Iperf 网络性能测试
  10. 区块链100讲:详解Po.et 技术栈
  11. 递归实现回旋数组的小程序
  12. 啊哈C语言 第八章 【代码】【习题答案】
  13. 毕业论文答辩ppt怎么做?
  14. 易班打卡——自动填写健康日报
  15. openid php steam,在Android中使用openID进行Steam登录
  16. 一篇文章读懂 Ad Network、Ad Exchange、DSP、SSP、DMP的区别?
  17. Longitudinal Statistics 纵向统计分析
  18. 安装Ubuntu VMware Workstation 不可恢复错误
  19. 5g nr,PDSCH/PUSCH,UE如何选择MCS table
  20. Unity3D关于ComputeShader

热门文章

  1. .net framework处理xml
  2. Android学习之反编译工具的使用
  3. 推荐好用的linux系统(manjaro)
  4. Codeup 墓地——1814: 剩下的树
  5. LeetCode:Rotate Image
  6. Spring AOP AspectJ
  7. 九章算术卷第一 方田
  8. 今日奇葩事件,一位不懂技术,却来管理技术团队的领导
  9. 《Groovy in Action》笔记
  10. qmail 反垃圾邮件