import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
//页面的布局
class FrameDemo
{
private JFrame fr;
private JTextArea jta1;
private JTextField jta2;
private JButton jb;
FrameDemo()
{
fr =new JFrame("QQ聊天界面");
jta1= new JTextArea(15,5); // 接受
jta2= new JTextField();//发送
jb= new JButton("发送");
fr.setBounds(200,300,400,600);
fr.setLayout(new BorderLayout(10,20));
fr.add(jta1,BorderLayout.NORTH);
fr.add(jta2,BorderLayout.SOUTH);
fr.add(jb,BorderLayout.CENTER);
fr.setVisible(true);
jta2.addActionListener(new myListener());
}
class SendDemo implements Runnable
{
private DatagramSocket ds ;
public void run()
{
try
{
ds= new DatagramSocket();
BufferedReader br = new BufferedReader(new FileReader(jta2.getText()));
String line=null;
while((line= br.readLine())!=null)
{
byte[] buf = line.getBytes();
DatagramPacket dp= new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),2668);
ds.send(dp);
}
}
catch (Exception e )
{
throw new RuntimeException("有问题111");
}
ds.close();
}
}
class ReceiveDemo implements Runnable
{
public void run()
{
try
{
DatagramSocket ds1 =new DatagramSocket(2668);
while (true ) // 这个是为了支持不停的循环读
{
byte[] bt =new byte[1024]; // 这个byte字节是用来暂时存储接受过来的数据
DatagramPacket dp1= new DatagramPacket(bt,bt.length);
ds1.receive(dp1);
String ip=dp1.getAddress().getHostAddress();
String content= new String(dp1.getData(),0,dp1.getLength());
jta1.append(ip+"::"+content);
}
}
catch (Exception e )
{
throw new RuntimeException("有问题2222");
}
}
}
class myListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
SendDemo sd= new SendDemo();
ReceiveDemo rd = new ReceiveDemo();
Thread sd1= new Thread(sd);
Thread rd1=new Thread(rd);
sd1.start();
rd1.start();
String name =jta2.getText();
jta1.append(name);
}
}
}
//开始写发送和接受机制 你想想啊 我已点击按钮 就要把我写在area中的数据发送出去
class UdpSendRe
{
public static void main(String[] args)
{
FrameDemo fd= new FrameDemo();
}
}
这是本人写的一个用UDP协议来实现QQ的聊天程序 调试了一天 编译没问题 但是 运行出现了大问题 可能是思想错了 求牛人解救?? |