GUI 聊天界面
import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.Event; import java.awt.Font; import java.awt.Frame; import java.awt.HeadlessException; import java.awt.Panel; import java.awt.TextArea; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.Date; import javax.management.ImmutableDescriptor; public class demon4_guiChat extends Frame{ private TextField tf; private Button send; private Button log; private Button clear; private Button shake; private TextArea viewText; private TextArea sendText; private DatagramSocket socket; private BufferedWriter bw; private BufferedReader br; /* * GUI 聊天 * 继承frame 可以使用frame 的所有方法 */ // vvvpackage com.heima.socket; public static void main(String[] args) throws Exception { //主方法 主线程 new demon4_guiChat(); } public demon4_guiChat() throws Exception { init(); //初始化 窗体 和开启接收信息的多线程 southPanel(); // 创建南边的panel centerPanel(); // 创建中间的panel event(); // 事件处理: } public void event() { this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { try { socket.close(); bw.close(); } catch (IOException e1) { e1.printStackTrace(); } System.exit(0); } }); send.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { send(); } catch (IOException e1) { e1.printStackTrace(); } } }); log.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { logFile(); } catch (IOException e1) { e1.printStackTrace(); } } }); clear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { viewText.setText(""); } }); shake.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { send(new byte[]{-1}, tf.getText()); } catch (IOException e1) { e1.printStackTrace(); } } }); sendText.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER && e.isControlDown()) { try { send(); } catch (IOException e1) { e1.printStackTrace(); } } } }); } private void shake() { int x = this.getLocation().x; int y = this.getLocation().y; for (int i = 0; i < 5 ; i++) { try { this.setLocation(x+10, y+10); Thread.sleep(20); this.setLocation(x+10, y-10); Thread.sleep(20); this.setLocation(x-10, y+10); Thread.sleep(20); this.setLocation(x-10, y-10); Thread.sleep(20); this.setLocation(x, y); } catch (InterruptedException e) { e.printStackTrace(); } } } private void logFile() throws IOException { bw.flush(); FileInputStream f1 = new FileInputStream("conifg.txt"); ByteArrayOutputStream b1 = new ByteArrayOutputStream(); // 在内存中创建缓冲区 int len ; byte[] arr = new byte[8192]; while ((len = f1.read(arr)) != -1) { b1.write(arr, 0, len); } String str = b1.toString(); viewText.setText(str); f1.close(); } private void send() throws IOException { String message = sendText.getText(); // 获取发送区域的内容 String ip = tf.getText(); //获取IP地址 ip = ip.trim().length() == 0 ? "255.255.255.255":ip; // 去掉前后空格 send(message.getBytes(), ip); //viewText.setText(message); //将信息显示在显示区 String time = getCurrentTime(); String sendStr = time + " 我对" + (ip.equals("255.255.255.255")?"所有人":ip) + "说:" + "\r\n" + message + "\r\n\r\n"; viewText.append(sendStr); // 将信息添加到显示区 bw.write(sendStr); sendText.setText(""); } public void send(byte[] arr, String ip) throws IOException { DatagramPacket packet = new DatagramPacket(arr, arr.length, InetAddress.getByName(ip), 8888); socket.send(packet); } private String getCurrentTime() { Date d = new Date(); //创建当前日期对象 SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); //大MM 小dd return sdf.format(d); //将时间格式化 } public void centerPanel() { Panel center = new Panel(); // 创建中间的panel viewText = new TextArea(); sendText = new TextArea(4,1); center.setLayout(new BorderLayout()); //设置为边界布局管理器 center.add(sendText,BorderLayout.SOUTH); center.add(viewText,BorderLayout.CENTER); viewText.setEditable(false); sendText.setEditable(true); sendText.setFont(new Font("xxx", Font.PLAIN, 14)); viewText.setFont(new Font("xxx", Font.PLAIN, 14)); viewText.setBackground(Color.gray); this.add(center,BorderLayout.CENTER); } public void southPanel() { Panel south = new Panel(); tf = new TextField(15); tf.setText("127.0.0.1"); send = new Button("发送"); log = new Button("记录"); clear = new Button("清屏"); shake = new Button("震动"); south.add(tf); // 将各组件添加到组件中 south.add(send); south.add(log); south.add(clear); south.add(shake); this.add(south,BorderLayout.SOUTH); //将panel 增加到frame中的南边 } public void init(){ // 初始化方法 this.setLocation(500, 50); this.setSize(400, 600); new receive().start(); try { socket = new DatagramSocket(); bw = new BufferedWriter(new FileWriter("conifg.txt",true)); bw.flush(); } catch (Exception e) { e.printStackTrace(); } this.setVisible(true); } class receive extends Thread{ // 接收发送需要同时执行 开启多线程 // 再类中创建类 可以方便使用外部类的方法和变量 可以使用viewText public void run() { try { DatagramSocket socket = new DatagramSocket(8888); DatagramPacket packet = new DatagramPacket(new byte[8192], 8192); while (true) { socket.receive(packet); byte[] arr = packet.getData(); int len = packet.getLength(); // 获取有效的字节数据 //System.out.println(len); //System.out.println(arr.length); if (arr[0] == -1 && len == 1) { shake(); continue; // 终止本次循环,开始下次循环 } String time = getCurrentTime(); String message = new String(arr, 0, len); //转换成字符串 String ip = packet.getAddress().getHostAddress(); String receiveStr = time + " " + ip + "对我说:\r\n" + message + "\r\n\r\n"; viewText.append(receiveStr); bw.write(receiveStr); } } catch (Exception e) { e.printStackTrace(); } } } }
竹杖芒鞋轻胜马,一蓑烟雨任平生。
回首向来萧瑟处,也无风雨也无晴。