1、用 Java 编写的 UDP 协议简单聊天室:package com;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import .*;public class Chat Frame frame = new Frame(“个人聊天室“);TextField tfip = new TextField(15);/ 用户输入 IP
2、地址的文本框List list = new List();/ 用于显示接收消息的列表框DatagramSocket ds;public Chat() try ds = new DatagramSocket(50000); catch (SocketException e) e.printStackTrace();new Thread(new Runnable() public void run() try byte buf = new byte1024;DatagramPacket dp = new DatagramPacket(buf, 1024);while (true) ds.recei
3、ve(dp);System.out.println(“接收 OK“);list.add(new String(buf, 0, dp.getLength() + “:from“+ dp.getAddress().getHostAddress(), 0); catch (Exception e) e.printStackTrace();).start();public static void main(String args) Chat chat = new Chat();chat.init();public void init() frame.setSize(300, 300);frame.ad
4、d(list);Panel p = new Panel();p.setLayout(new BorderLayout();/ p.add(tfip,“West“);p.add(“West“, tfip);TextField tfdata = new TextField(20);p.add(“East“, tfdata);frame.add(“South“, p);frame.setVisible(true);frame.setResizable(false);/ 限制用户设置窗体的大小frame.addWindowListener(new WindowAdapter() public void
5、 windowClosing(WindowEvent e) frame.setVisible(false);frame.dispose();System.exit(0););tfdata.addActionListener(new ActionListener() public void actionPerformed(ActionEvent e) / 有关网络发送信息的动作byte buf = e.getActionCommand().getBytes();try DatagramPacket dp = new DatagramPacket(buf, buf.length,InetAddress.getByName(tfip.getText(), 50000);ds.send(dp); catch (Exception e1) e1.printStackTrace();(TextField) e.getSource().setText(“);/ 清空文本框内容);/ 填写完内容后按下回车所触发的事件