资源预览内容
第1页 / 共3页
第2页 / 共3页
第3页 / 共3页
亲,该文档总共3页全部预览完了,如果喜欢就下载吧!
资源描述
用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 byte1024;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();/ 清空文本框内容);/ 填写完内容后按下回车所触发的事件
收藏 下载该资源
网站客服QQ:2055934822
金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号