- package 鸿雁;
- import java.awt.*;
- import java.awt.event.*;
- import java.net.*;
- public class Chat extends Frame{
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- //Frame f = new Frame("林林的聊天室");
- /* tfIP 是用于输入IP 地址的文本框,在发送数据时,要取出其中的IP 地址,所以将其定义成员变
- 量,以便发送消息的程序代码访问。*/
- TextField tfIP = new TextField(15);
- /*lst 是用于显示接收消息的列表框,在接收到数据时,要向其中增加新的记录项,所以将其定义成员
- 变量,以便接收消息的程序代码访问。*/
- List lst = new List(6);
- DatagramSocket ds;
- Image iMainWinBkg = null;
- /*由于DatagramSocket 的构造函数声明可能抛出异常,我们的程序需要用try…catch 语句进行异
- 常捕获处理,所以我们不能直接在这里调用DatagramSocket的构造函数对ds进行初始化,我们需要将ds
- 的初始化放在Chat类的构造函数中去完成。*/
- public Chat() {
- try {
- ds = new DatagramSocket(3000);
- } catch (Exception ex) {
- // TODO: handle exception
- ex.printStackTrace();
- }
- /*接收程序代码在一个新的线程中完成,这样,在接收处于阻塞状态时,不会影响到程序的发送部分。*/
- new Thread(new Runnable() {
- @Override
- public void run() {
- // TODO Auto-generated method stub
- byte [] buf = new byte[1024];
- DatagramPacket dp = new DatagramPacket(buf, 1024);
- while (true) {
- try {
- ds.receive(dp);
- lst.add(new String(buf, 0, dp.getLength())
- + " from "
- + dp.getAddress().getHostAddress()
- + ": "
- + dp.getAddress().getHostName().toString()
- + ", 端口号: "
- + dp.getPort(), 0);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }).start();
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Chat mChat = new Chat();
- mChat.init();
- }
- public void init() {
- try {
- tfIP.setText(InetAddress.getLocalHost().getHostAddress().toString());
- } catch (Exception e3) {
- // TODO Auto-generated catch block
- e3.printStackTrace();
- }
- this.setTitle("林林的聊天室");
- this.setSize(640, 480);
- this.setLocation((java.awt.Toolkit.getDefaultToolkit().getScreenSize().width - this.getWidth()) / 2,
- (java.awt.Toolkit.getDefaultToolkit().getScreenSize().height- this.getHeight()) / 2);
- String creAccBkPath = "mainWinBkg.jpg"; // relative path of background picture.
- iMainWinBkg = this.getToolkit().getImage(creAccBkPath); // background image.
- //f.setBackground(new Color(100, 150, 200)); // set background color
- this.add(lst);
- Panel p = new Panel();
- p.setLayout(new BorderLayout());
- p.add("West", tfIP);
- TextField tfData = new TextField(68);
- p.add("East", tfData);
- this.add("South", p);
- this.setVisible(true);
- //this.setLayout(null); // set layout so that buttons on f window is free to change size and location.
- this.setResizable(false); // can't change size of the window.
- //f.setUndecorated(true);
- this.addWindowListener(new MainWindowListener(ds)); // register window listener for closing.
- //增加在消息文本框中按下回车键的事件处理代码
- tfData.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- //要在这里增加网络消息发送相关程序代码
- //取出文本框中的消息字符串,并将其转换成字节数组
- byte[] buf;
- buf = e.getActionCommand().getBytes();
- DatagramPacket dp = null;
- try {
- dp = new DatagramPacket(buf, buf.length, InetAddress.getByName(tfIP.getText()), 3000);
- } catch (UnknownHostException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- try {
- ds.send(dp);
- } catch (Exception e2) {
- // TODO: handle exception
- e2.printStackTrace();
- }
- //下面的语句用于数据发送后,清空文本框中原来的内容
- ((TextField)e.getSource()).setText("");
- }
- });
- //CreAccYesBtn mCreAccYesBtn = new CreAccYesBtn();
- //mCreAccYesBtn.addYesBtn(f);
- }
- public void paint(Graphics g) {
- getGraphics().drawImage(iMainWinBkg, -370, 0, this);
- }
- }
- class MainWindowListener extends WindowAdapter
- {
- DatagramSocket mds;
- public MainWindowListener(DatagramSocket ds) {
- mds = ds;
- }
- public void windowClosing(WindowEvent e)
- {
- mds.close(); //程序退出时,关闭Socket,释放相关资源
- //ystem.out.println(ss);
- e.getWindow().setVisible(false);
- ((Window)e.getComponent()).dispose(); // release all resources used by this window.
- System.exit(0);
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/0501201511479.html
来源: http://www.codesnippet.cn/detail/0501201511479.html