本帖最后由 梁航斌 于 2013-4-8 08:51 编辑
自己看完视频后弄的小聊天程序一枚,遇到一点问题。直接上源码了。问题在下面。怎么解决呢?还有代码还可以怎么优化?还要注意哪些隐患- package mytalkDemo;
- import java.awt.*;
- import java.awt.event.*;
- import java.net.*;
- import java.io.*;
- public class awtDemo
- {
-
- public static void main(String []args) throws Exception{
- //创建DatagramSocket对象
- DatagramSocket sds = new DatagramSocket();
- DatagramSocket rds = new DatagramSocket(10010);
- //创建一个Ui
- awtUi au = new awtUi(sds);
- //开启一个线程用来接收信息
- new Thread(new recDemo(rds,au.show)).start();
- }
- }
- //Ui组件
- class awtUi
- {
- //定义控件
- private Frame f;
- private Button b;
- public TextArea show;
- private TextArea talk;
- //创建DatagramSocket对象
- private DatagramSocket sds;
- //加载控件
- awtUi(DatagramSocket sds){
- this.sds = sds;
- init();
- }
- //控件初始化
- public void init(){
- f = new Frame("我的聊天软件");
- b = new Button("发送");
- show = new TextArea();
- talk = new TextArea();
- f.setLayout(new FlowLayout());
- f.setBounds(200,100,400,500);
- show.setColumns(50);
- show.setRows(15);
- f.add(show);
- talk.setColumns(50);
- talk.setRows(8);
- f.add(talk);
- f.add(b);
- f.setVisible(true);
- event();
- }
- //初始化监听事件
- public void event(){
- f.addWindowListener(new WindowAdapter(){
- public void windowClosing(WindowEvent e){
- System.exit(0);
- }
- });
- talk.addKeyListener(new KeyAdapter(){
- public void keyPressed(KeyEvent e){
- if(e.isControlDown()&&e.getKeyCode() == e.VK_ENTER){
- try{
- sendfuntion();
- }
- catch(Exception ex){
- throw new RuntimeException("发送失败");
- }
- }
- }
- });
- b.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent e){
- try{
- sendfuntion();
- }
- catch(Exception ex){
- throw new RuntimeException("发送失败");
- }
- }
- });
- }
- //发送数据方法
- public void sendfuntion() throws Exception{
- String ts = talk.getText();
- byte []buf = ts.getBytes();
- DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.255"),10010);
- sds.send(dp);
- talk.setText("");
- }
- }
- //这里有点疑惑
- class recDemo implements Runnable
- {
-
- private TextArea show;
- private DatagramSocket rds;
- recDemo(DatagramSocket rds,TextArea show){
- this.rds = rds;
- this.show = show;
- }
- public void run(){
- try{
- while(true){
- byte []buf = new byte[1024];
- DatagramPacket dp = new DatagramPacket(buf,buf.length);
- rds.receive(dp);
- String ip = dp.getAddress().getHostAddress();
- //这里该怎么判断ip如果是自己的就替换成me呢?
- /*if(ip.equals(InetAddress.getByName("127.0.0.1").getHostAddress())){
- ip = "Me";
- */}
- String data = new String(dp.getData(),0,dp.getLength());
- show.append(ip+": "+data+"\r\n");
- }
- }
- catch(Exception e){
- throw new RuntimeException("接收失败");
- }
- }
- }
复制代码
|