|
源程序:
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public class Chat
{
Frame f=new Frame("fish_liang聊天室");
TextField tfIP=new TextField(15);
List lst=new List(6);
DatagramSocket ds;
public Chat()
{
try
{
ds=new DatagramSocket(6000);
}
catch(Exception e)
{
System.out.println("Socket初始化6000端口失败");
}
new Thread(new Runnable()
{
public void run()
{
byte buf[]=new byte[1020];
DatagramPacket dp=new DatagramPacket(buf,1024);
while(true)
{
try
{
ds.receive(dp);
lst.add(new String(buf,0,dp.getLength())+":from"+dp.getAddress().getHostAddress(),0);
}
catch(Exception e)
{
System.out.println("消息接收失败");
}
}
}
}).start();
}
public static void main(String args[])
{
Chat chat=new Chat();
chat.init();
}
public void init()
{
f.setSize(300,300);
f.add(lst);
Panel p=new Panel();
p.setLayout(new BorderLayout());
p.add("West",tfIP);
TextField tfData=new TextField(20);
p.add("East",tfData);
f.add("South",p);
f.setVisible(true);
f.setResizable(false);
//关闭窗口的事件处理代码
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
ds.close();
f.setVisible(false);
f.dispose();
System.exit(0);
}
});
//在消息文本框中按下回车键的事件处理代码
tfData.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//网络消息发送相关程序代码
byte[] buf;
buf=e.getActionCommand().getBytes();
DatagramPacket dp;
try
{
dp=new DatagramPacket(buf,buf.length,InetAddress.getByName(tfIP.getText()),6000);
ds.send(dp);
}
catch(Exception ex)
{
System.out.println("消息发送失败");
}
((TextField)e.getSource()).setText(""); //用于数据发送后,清空文文本框原来的内容
}
});
}
}
-------------------------------------------------------------------------------------
运行后,发送消息出去,死表List无任何内容!!??
请各位大哥帮我看一下上面的代码,看看是哪里出错,还是怎么回事?!!
谢谢~~~~~~~~~~
等ING~~~~~~~~~~~~~ |
|