用Java编写的UDP协议简单聊天室

用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 java.net.*;

public class Chat {
 Frame frame = new Frame("个人聊天室");
 TextField tfip = new TextField(15);// 用户输入IP地址的文本框
 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 byte[1024];
     DatagramPacket dp = new DatagramPacket(buf, 1024);
     while (true) {
      ds.receive(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.add(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 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("");// 清空文本框内容

   }

  });// 填写完内容后按下回车所触发的事件

 }

}

你可能感兴趣的:(用Java编写的UDP协议简单聊天室)