局域网聊天

来源:互联网 发布:雾霾 抽烟 知乎 编辑:程序博客网 时间:2024/04/28 21:00
package com.chat;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Chat extends JFrame {
 /**
  *
  */
 private static final long serialVersionUID = 1L;
 private JPanel m_contentPane;
 private JTextField txtName;
 private JTextArea txtEditor;
 private static JTextArea txtReceive;
 private static MulticastSocket socket;
 private static InetAddress groupAdd;
 private JComboBox cmbFeel;
 private String[] Feel;
 private JMenuBar menuBar;
 private JMenu File;
 private JMenuItem Quit;
 private JMenuItem About;
 private JPopupMenu popMenu;
 private JMenuItem Copy;
 private JMenuItem ClearAll;
 private JScrollPane scrollPane;
 private JButton btnSend;
 // private JScrollPane JScRece;
 /**
  * Launch the application.
  */
 public static void main(String[] args) {
  // final ReceiveMsg recMsg = new ReceiveMsg(socket);
  try {
   groupAdd = InetAddress.getByName("255.255.255.255");
  } catch (UnknownHostException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
  try {
   socket = new MulticastSocket(60000);
  } catch (IOException e1) {
   e1.printStackTrace();
  }
  //  
  // try {
  // socket.joinGroup(groupAdd);
  // } catch (IOException e1) {
  // e1.printStackTrace();
  // }
  /**
   * 定义接收数据的内部类
   *
   * @author Administrator
   *
   */
  class ReceiveMsg extends Thread {
   MulticastSocket s = null;
   public ReceiveMsg(MulticastSocket s) {
    this.s = s;
   }
   public void run() {
    byte[] buf = new byte[1024];
    DatagramPacket recv = new DatagramPacket(buf, buf.length);
    try {
     while (true) {
      s.receive(recv);
      InetAddress recvIp = recv.getAddress();
      String strRecvIP = recvIp.toString().substring(1);
      String strLocalIP = InetAddress.getLocalHost()
        .getHostAddress();
      //       
      if (!strRecvIP.equals(strLocalIP))
      // // 判定发送数据的是否是本机
      {
//       Font font = new Font();
       SimpleDateFormat dateFormat = new SimpleDateFormat(
         "HH:mm:ss");
       String str = new String(recv.getData(), 0, recv
         .getLength());
       String message = null;
       // System.out.println(str.indexOf(':'));
       if ((str.indexOf(':') > 0)
         || (str.indexOf(":") > 0)) {
        message = str.substring(0, str.indexOf(':'))
          + ":" + dateFormat.format(new Date())
          + "/n       "
          + str.substring(str.indexOf(":") + 1);
       }
       String line = System.getProperty("line.separator");
       txtReceive.append(message);
       txtReceive.append(line);
      }
     }
    } catch (IOException e2) {
     System.out.println("接收失败!");
    }
   }
  }
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     Chat chatFrame = new Chat();
     ReceiveMsg r = new ReceiveMsg(socket);
     r.start();
     chatFrame.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }
 /**
  * Create the frame.
  *
  * @throws IOException
  */
 public Chat() throws IOException {
  addWindowListener(new WindowAdapter() {
   public void windowOpened(WindowEvent e) {
    txtEditor.requestFocus();
//    btnSend.requestFocus();
   }
  });
  setResizable(false);
  setTitle("UDPChat");
  {
   menuBar = new JMenuBar();
   setJMenuBar(menuBar);
   {
    File = new JMenu("/u6587/u4EF6");
    menuBar.add(File);
    {
     Quit = new JMenuItem("/u9000/u51FA");
     Quit.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
       System.exit(1);
      }
     });
     File.add(Quit);
    }
   }
   {
    JMenu Help = new JMenu("/u5E2E/u52A9");
    menuBar.add(Help);
    {
     About = new JMenuItem("/u5173/u4E8E");
     About.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
       JOptionPane.showMessageDialog(null, "这是个局域网聊天",
         "About", JOptionPane.INFORMATION_MESSAGE);
      }
     });
     Help.add(About);
    }
   }
  }
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setBounds(100, 100, 512, 502);
  m_contentPane = new JPanel();
  m_contentPane.setToolTipText("");
  m_contentPane.setLayout(null);
  m_contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  Feel = new String[] { "笑着", "哭着", "大笑" };
  setContentPane(m_contentPane);
  {
   JSeparator separator = new JSeparator();
   separator.setBounds(10, 302, 481, 2);
   m_contentPane.add(separator);
  }
  {
   JLabel label = new JLabel("/u6635/u79F0/uFF1A");
   label.setBounds(10, 317, 54, 15);
   m_contentPane.add(label);
  }
  {
   txtName = new JTextField("ywang");
   txtName.addFocusListener(new FocusAdapter() {
    public void focusLost(FocusEvent e) {
     if (!Pattern.matches("^([A-Z]|[a-z])*[^::]*", txtName
       .getText())) {
      JOptionPane.showMessageDialog(null, "名字不能含有特殊字符", "提示",
        JOptionPane.ERROR_MESSAGE);
      return;
     }
    }
   });
   txtName.setBounds(45, 314, 82, 21);
   m_contentPane.add(txtName);
   txtName.setColumns(10);
  }
  {
   JLabel label = new JLabel("/u8868/u60C5/uFF1A");
   label.setBounds(146, 318, 54, 15);
   m_contentPane.add(label);
  }
  {
   cmbFeel = new JComboBox(Feel);
   cmbFeel.setBounds(185, 314, 82, 23);
   m_contentPane.add(cmbFeel);
  }
  /**
   * 定义发送数据事件类
   *
   * @author Administrator
   *
   */
  class SendMsg implements ActionListener {
   String msg = null;
   MulticastSocket s = null;
   InetAddress group = null;
   public SendMsg(MulticastSocket s, InetAddress group) {
    this.s = s;
    this.group = group;
   }
   @Override
   public void actionPerformed(ActionEvent e) {
    try {
     if (txtName.getText().isEmpty()) {
      JOptionPane.showMessageDialog(null, "请一定输入别名!");
     } else {
      SimpleDateFormat dateFormat = new SimpleDateFormat(
        "HH:mm:ss");
      msg = (txtName.getText() + cmbFeel.getSelectedItem()
        + "说:"+ dateFormat.format(new Date())
        + "/n       " + txtEditor.getText());
        
      // 在msg中 + "/n"
      // 可以替代System.getproperty("line.separator");
      // txtReceive.append(line);
      if (txtEditor.getText().isEmpty()) {
       JOptionPane.showMessageDialog(null, "不能发送空消息!",
         "提示 ", JOptionPane.ERROR_MESSAGE);
      } else {
       txtEditor.setText("");
       DatagramPacket data = new DatagramPacket(msg
         .getBytes(), msg.getBytes().length, group,
         60000);
       s.send(data);
       txtReceive.append(msg + "/n");
      }
     }
    } catch (IOException e1) {
     e1.printStackTrace();
    }
    txtEditor.requestFocus();
    
   }
  }
  {
   btnSend = new JButton("/u53D1/u9001");
   btnSend.setFont(new Font("宋体", Font.PLAIN, 12));
   btnSend.addActionListener(new SendMsg(socket, groupAdd));
   btnSend.setBounds(403, 343, 76, 42);
   m_contentPane.add(btnSend);
  }
  {
   txtEditor = new JTextArea();
   txtEditor.setTabSize(1);
   txtEditor.setBounds(10, 343, 365, 102);
   m_contentPane.add(txtEditor);
  }
  {
   JButton btnQuit = new JButton("/u9000/u51FA");
   btnQuit.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
     System.exit(1);
    }
   });
   btnQuit.setBounds(403, 403, 76, 42);
   m_contentPane.add(btnQuit);
  }
  txtReceive = new JTextArea();
  {
   popMenu = new JPopupMenu();
   addPopup(txtReceive, popMenu);
   {
    Copy = new JMenuItem("/u590D/u5236");
    Copy.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
      txtReceive.copy();
     }
    });
    popMenu.add(Copy);
   }
   {
    ClearAll = new JMenuItem("/u6E05/u5C4F");
    ClearAll.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
      txtReceive.setText("");
     }
    });
    popMenu.add(ClearAll);
   }
  }
  txtReceive.setBounds(10, 10, 481, 282);
  txtReceive.setEditable(false);
  scrollPane = new JScrollPane();
  scrollPane.setViewportView(txtReceive);
  scrollPane.setBounds(10, 10, 483, 285);
  m_contentPane.add(scrollPane);
 }
 private static void addPopup(Component component, final JPopupMenu popup) {
  component.addMouseListener(new MouseAdapter() {
   public void mousePressed(MouseEvent e) {
    if (e.isPopupTrigger()) {
     showMenu(e);
    }
   }
   public void mouseReleased(MouseEvent e) {
    if (e.isPopupTrigger()) {
     showMenu(e);
    }
   }
   private void showMenu(MouseEvent e) {
    popup.show(e.getComponent(), e.getX(), e.getY());
   }
  });
 }
}
 
文中红色部分定义的类为什么要放在main方法中呢?
别的方法改怎么写?
原创粉丝点击