8.03_网络编程(GUI聊天小程序)

 

一、小程序效果图

  

二、代码

  public class MyFrame extends JFrame {
  private static final long serialVersionUID = 1L;
  private JPanel jp1,jp2;
  private JButton jb1,jb2,jb3,jb4;
  private JTextField jtf1;
  private JTextArea jta1,jta2;
  private JScrollPane jsp1,jsp2;
  DatagramSocket scoket;
  BufferedWriter bw;
  private LogFileDialog ld;
  public MyFrame() {
    centerPanel();
    southPanel();
    init();
    sendsf();

    }


  public void centerPanel() {
    jp1 = new JPanel();
    jta1 = new JTextArea();
    jta2 = new JTextArea(5,1);
    jsp1 = new JScrollPane(jta1);
    jsp2 = new JScrollPane(jta2);
    jta1.setEditable(false);
    jta1.setBackground(Color.WHITE);
    jta1.setFont(new Font("sdds", Font.PLAIN, 15));
    jta2.setFont(new Font("sdds", Font.PLAIN, 15));
    jp1.setLayout(new BorderLayout());
    jp1.add(jsp2,BorderLayout.SOUTH);jp1.add(jsp1,BorderLayout.CENTER);
    this.add(jp1,BorderLayout.CENTER);
  }
    public void southPanel() {
    jp2 = new JPanel();
    jb1 = new JButton("发送");
    jb2 = new JButton("记录");
    jb3 = new JButton("清屏");
    jb4 = new JButton("震动");
    jtf1 = new JTextField(15);
    jtf1.setText("127.0.0.1");
    jp2.add(jtf1);jp2.add(jb1);jp2.add(jb2);jp2.add(jb3);jp2.add(jb4);
    this.add(jp2,BorderLayout.SOUTH);
  }

   public void init() {
    this.setSize(530, 550);
    this.setLocation(300,100);
    this.setTitle("飞飞飞球");
    try {
      scoket = new DatagramSocket();
      bw = new BufferedWriter(new FileWriter("cofing.txt",true));
    } catch (Exception e) {
      e.printStackTrace();
    }
      new Receive().start();
      this.setVisible(true);
    }
    public void sendsf() {
      this.addWindowListener(new WindowAdapter() {
      @Override
      public void windowClosing(WindowEvent e) {
      scoket.close();
      try {
        bw.close();
      } catch (IOException e1) {
        e1.printStackTrace();
      }
        System.exit(0);
      }
    });
      jb1.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
    try {
      send();
    } catch (IOException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
  }

});
  jb2.addActionListener(new ActionListener() {

  @Override
    public void actionPerformed(ActionEvent e) {
    try {
      logFile();
    } catch (IOException e1) {
      e1.printStackTrace();
    }

  }

});
    jb3.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
      jta1.setText("");

  }
});
    jb4.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
      try {
      send(new byte[] {-1},jtf1.getText() );
      } catch (UnknownHostException e1) {
        e1.printStackTrace();
      } catch (IOException e1) {
        e1.printStackTrace();
      }
  }
  });
      jta2.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
        try {
          //if(e.getKeyCode()==KeyEvent.VK_ENTER&&e.isControlDown()) {//isControlDown() ctrl是否被按下
          if(e.getKeyCode()==KeyEvent.VK_ENTER){
            send();
          }
        } catch (IOException e1) {
          e1.printStackTrace();
       }
    }
  });
}
      private void sake() {
      int x= this.getLocation().x;
      int y = this.getLocation().y;
      for(int i=0;i<15;i++) {
      try {
        this.setLocation(x+14, y+15);
        Thread.sleep(10);
        this.setLocation(x+14, y-16);
        Thread.sleep(10);
        this.setLocation(x-16, y+17);
        Thread.sleep(10);
        this.setLocation(x-16, y-17);
        Thread.sleep(10);
        this.setLocation(x, y);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
  }
      private void logFile() throws IOException {
        bw.flush();

      FileInputStream fis = new FileInputStream("cofing.txt");
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      byte[] arr = new byte[8819];
      int len;
      while((len=fis.read(arr))!=-1) {
      bos.write(arr,0,len);
    }
      String jilu=bos.toString();
      bos.close();
      ld = new LogFileDialog(jilu);
      ld.setVisible(true);
  }
      private void send() throws IOException {
      String str1 = jta2.getText();
      String ip = jtf1.getText();
      ip = ip.trim().length()==0?"255.255.255.255":ip;
      send(str1.getBytes(), ip);
      String time = getTime();
      String str = time +" 我对"+(ip.equals("255.255.255.255")?"所有人":ip)+"说:\r\n"+str1+"\r\n\r\n";
      bw.write(str);
      jta1.append(str);
      jta2.setText("");
  }


    public void send(byte[] arr, String ip) throws UnknownHostException, IOException {
      DatagramPacket packet = new DatagramPacket(
      arr, arr.length,InetAddress.getByName(ip), 6666);
        scoket.send(packet);
    }


    private String getTime() {
      SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date da = new Date();
      return sf.format(da);
  }
    private class Receive extends Thread{
      @Override
      public void run() {
      try {
        DatagramSocket scoket = new DatagramSocket(6666);
        DatagramPacket packet = new DatagramPacket(new byte[8192], 8192);
      while(true) {
        scoket.receive(packet);
        byte[] array = packet.getData();
        int len = packet.getLength();
        if(array[0]==-1&&len==1) {
          sake();
          continue;
        }
          String time = getTime();
          String ip = packet.getAddress().getHostAddress();
          String measg = new String(array,0,len);
          String str = time+" "+ip+" 对我说:\r\n"+measg+"\r\n\r\n";
          bw.write(str);
          jta1.append(str);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
    class LogFileDialog extends JDialog{
      private JTextArea jta;
      private JScrollPane jsp;
      public String jilu;
      public LogFileDialog(String jilu) {
        this.jilu=jilu;
        this.setTitle("聊天记录");
        this.setSize(430,440);
        this.setLocation(400, 120);
        jta = new JTextArea();
        jsp = new JScrollPane(jta);
        jta.setText(jilu);
        this.add(jsp);
    }
  }

posted @ 2020-03-11 16:16  mz张洋洋  阅读(159)  评论(0编辑  收藏  举报