欢迎来到天天文库
浏览记录
ID:13203539
大小:23.50 KB
页数:3页
时间:2018-07-21
《用java编写的udp协议简单聊天室》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、用Java编写的UDP协议简单聊天室:packagecom;importjava.awt.*;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.awt.event.WindowAdapter;importjava.awt.event.WindowEvent;importjava.net.*;publicclassChat{Frameframe=newFrame("个人聊天室");TextFieldtfip=newTextField(15);//用户输入IP地址
2、的文本框Listlist=newList();//用于显示接收消息的列表框DatagramSocketds;publicChat(){try{ds=newDatagramSocket(50000);}catch(SocketExceptione){e.printStackTrace();}newThread(newRunnable(){publicvoidrun(){try{bytebuf[]=newbyte[1024];DatagramPacketdp=newDatagramPacket(buf,1024);while(true){ds.receive(dp);Sy
3、stem.out.println("接收OK");list.add(newString(buf,0,dp.getLength())+":from"+dp.getAddress().getHostAddress(),0);}}catch(Exceptione){e.printStackTrace();}}}).start();}publicstaticvoidmain(String[]args){Chatchat=newChat();chat.init();}publicvoidinit(){frame.setSize(300,300);frame.add(list);
4、Panelp=newPanel();p.setLayout(newBorderLayout());//p.add(tfip,"West");p.add("West",tfip);TextFieldtfdata=newTextField(20);p.add("East",tfdata);frame.add("South",p);frame.setVisible(true);frame.setResizable(false);//限制用户设置窗体的大小frame.addWindowListener(newWindowAdapter(){publicvoidwindowCl
5、osing(WindowEvente){frame.setVisible(false);frame.dispose();System.exit(0);}});tfdata.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){//有关网络发送信息的动作byte[]buf=e.getActionCommand().getBytes();try{DatagramPacketdp=newDatagramPacket(buf,buf.length,InetAddress.ge
6、tByName(tfip.getText()),50000);ds.send(dp);}catch(Exceptione1){e1.printStackTrace();}((TextField)e.getSource()).setText("");//清空文本框内容}});//填写完内容后按下回车所触发的事件}}
此文档下载收益归作者所有