本帖最后由 黑马任雪刚 于 2012-6-1 15:38 编辑
//需求:一个简单的窗体,能够实现最基本的聊天功能。
//但是功能实现不了,求高手指导!!!!!!!!!!!!!!!
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
//负责发送信息的类。
class Send implements Runnable
{
DatagramSocket sds;
Jf j;
public Send(DatagramSocket sds,Jf j)
{
this.j = j;
this.sds=sds;
}
//覆盖run()方法。
public void run()
{
System.out.println("发送来了!");
//按钮事件。
j.b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent v)
{
System.out.println("点击了发送!");
File f=new File("c:\\","chat.txt");
BufferedReader br = null;
BufferedWriter bw = null;
DatagramPacket dp = null;
try
{
bw=new BufferedWriter(new FileWriter(f));
String s = j.ta2.getText();
bw.write(s);
System.out.println("制造发送");
b = new BufferedReader(new FileReader(f));
String line = null;
//System.out.println(1);
while((line=br.readLine())!=null)//为什么程序执行到这儿的时候,总会卡掉呢???
//信息发送不出去!!!是while循环的问题吗???求高人指教!!!
{
//System.out.println(2);
byte[] buf = line.getBytes();
//System.out.println(3);
dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),10008);
//System.out.println(4);
System.out.println("发送前!");
sds.send(dp);
System.out.println("发送成功!");
j.ta1.append(dp.getAddress().getHostAddress()+s+"\r\n");
j.ta2.setText("");
}
}
catch(Exception e)
{
throw new RuntimeException("写入失败!");
}
finally
{
if(bw!=null)
{
try
{
bw.close();
}
catch(Exception e)
{
throw new RuntimeException("发送端失败!");
}
}
if(br!=null)
{
try
{
br.close();
}
catch(Exception e)
{
throw new RuntimeException("发送端失败!");
}
}
}
}
});
}
}
//负责接收信息的类。
class Receive implements Runnable
{
private DatagramSocket rds;
private Jf j;
Receive(DatagramSocket rds,Jf j)
{
this.j = j;
this.rds = rds;
}
public void run()
{
try
{
while(true)
{
System.out.println("来了!");
byte[] buf = new byte[1024*64];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
rds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
j.t.setText("");
j.t.setText("与"+ip+"聊天中"+"");
j.ta1.append(ip+"..."+data+"\r\n");
}
}
catch(Exception e)
{
throw new RuntimeException("接受端失败!");
}
}
}
//创建窗口类。
class Jf
{
Frame f;
TextField t;
TextArea ta1,ta2;
Button b;
Jf()
{
cf();
}
//创建一个窗口的方法。
public void cf()
{
f = new Frame("QQ");
f.setSize(500,450);
f.setLocation(100,200);
f.setLayout(new FlowLayout());
t=new TextField(20);
ta1 = new TextArea(10,60);
b = new Button("发送");
ta2 = new TextArea(6,60);
f.add(t);
f.add(ta1);
f.add(ta2);
f.add(b);
ce();
f.setVisible(true);
}
//创建事件的方法。
public void ce()
{
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}
//主函数。
public class Chat
{
public static void main(String[] args)throws Exception
{
Jf j = new Jf();
DatagramSocket sds = new DatagramSocket();
DatagramSocket rds = new DatagramSocket(10008);
new Thread(new Receive(rds,j)).start();
new Thread(new Send(sds,j)).start();
}
}
|