本帖最后由 牛海亮 于 2013-7-17 14:12 编辑
我也一直想做一个,做了一上午,终于做出来了,代码如下:- package udpChat;
- import java.awt.*;
- import java.awt.event.*;
- import java.io.File;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- public class UdpChatFrame {
- private Frame f;
- private TextField tf;
- private Button but;
- private Button butSend;
- private TextArea taReceive;// 数据接收窗口
- private TextArea taSend;// 数据发送窗口
- private Dialog d;// 用于校验IP地址
- private Label receiveLab;
- private Label sendLab;
- private Button okBut;// 对话框上的确定按钮
-
- public String ip;
- UdpChatFrame() {
-
- }
- //创建窗体,开启线程
- public void init() {
- f = new Frame("Udp聊天框");
- f.setBounds(300, 100, 600, 500);
- f.setLayout(new FlowLayout());
- tf = new TextField(70);
- but = new Button("连接");
- taReceive = new TextArea(10, 60);
- taSend = new TextArea(10, 60);
- receiveLab = new Label("接收信息:");
- sendLab = new Label("发送信息:");
- butSend = new Button("发送");
- f.add(tf);
- f.add(but);
- f.add(receiveLab);
- f.add(taReceive);
- f.add(sendLab);
- f.add(taSend);
- f.add(butSend);
-
- //开启一个接收线程用于不断地接收输入的信息
- new Thread(new ReceiveThread()).start();
- myEvent();
-
- f.setVisible(true);
- }
- private void myEvent() {
- //监听 连接 按钮
- but.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- ip = tf.getText();
- taReceive.append("开始和" + ip + "主机对话吧......" + "\r\n");
- taReceive.append("---------------------------------------"
- + "\r\n");
-
-
- }
- });
- //监听 发送 按钮
- butSend.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- String message = taSend.getText();
- taReceive.append("我:" + message + "\r\n");
- send(message);
- taSend.setText("");
- }
- });
- f.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- System.exit(0);
- }
- });
- }
- //发送 方法
- public void send(String message)
- {
- try
- {
- DatagramSocket ds = new DatagramSocket();
- byte[] buf = message.getBytes();
- //将缓冲区中的数据打包,用于发送。
- DatagramPacket dp =
- new DatagramPacket(buf, buf.length,InetAddress.getByName(ip), 10086);
- ds.send(dp);
-
-
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
-
- }
-
- //内部类 用于接收
- public class ReceiveThread implements Runnable {
- private DatagramSocket receiveDs;
- public void setReceiveDs()
- {
- try
- {
- this.receiveDs = new DatagramSocket(10086);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- //一创建就 标好端口号
- ReceiveThread()
- {
- setReceiveDs();
- }
-
- public void run() {
- try
- {
- while(true)
- {
- byte[] buf = new byte[1024];
- //将接收缓冲区封装起来,用于存放接收到的数据。
- DatagramPacket dp = new DatagramPacket(buf, buf.length);
- receiveDs.receive(dp);
- String data = new String(dp.getData(),0,dp.getLength());
-
- taReceive.append("他:"+data+"\r\n");
-
- }
-
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
-
- }
-
- }
复制代码 |