看完了java基础视频,自己用udp编一个简单的带图形化界面的qq程序,运行的时候总是报错,报的错是空指针和socket closed,但是找不到啊,求高人指点啊。。。
代码如下:
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
class Awt
{
private Frame f;
private TextArea area;
private TextField field;
public void awtFrame() throws Exception
{
f=new Frame("对话中");
f.setLayout(new FlowLayout());
f.setBounds(400,300,600,500);
area=new TextArea(20,60);
field=new TextField(30);
f.add(area);
f.add(field);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
f.setVisible(true);
}
public Frame getf()
{
return f;
}
public TextArea getta()
{
return area;
}
public TextField gettf()
{
return field;
}
}
class QQTest
{
public static void main(String[] args) throws Exception
{
Awt awt=new Awt();
awt.awtFrame();
DatagramSocket socket1=new DatagramSocket();
DatagramSocket socket2=new DatagramSocket(10006);
new Thread(new Receive(socket2,awt)).start();
new Thread(new Send(socket1,awt)).start();
}
}
class Send implements Runnable //需要文本框,窗体,文本区域。
{
private DatagramSocket socket;
private Awt awt;
Send(DatagramSocket socket,Awt awt)
{
this.socket=socket;
this.awt=awt;
}
byte[] buf=null;
public void run()
{
try
{
awt.getf().addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
String str=awt.gettf().getText();
buf=str.getBytes();
awt.getta().append(str);
}
}
});
DatagramPacket packet=new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.255"),10006);
socket.send(packet);
awt.gettf().setText("");
//packet.setData(buf);
}
catch (Exception ex)
{
System.out.println(ex.getMessage()+"==="+ex.toString());//throw new RuntimeException("发送错误");//==========
}
finally
{
socket.close();
}
}
}
class Receive implements Runnable//需要文本区域
{
private DatagramSocket socket;
private Awt awt;
Receive(DatagramSocket socket,Awt awt)
{
this.socket=socket;
this.awt=awt;
}
public void run()
{
try
{
byte[] buf=new byte[1024*1024*64];
DatagramPacket packet=new DatagramPacket(buf,buf.length);
socket.receive(packet);
String ip=packet.getAddress().getHostName();
String data=new String(packet.getData(),0,packet.getLength());
awt.getta().append(ip+":"+data);
}
catch (Exception ex)
{
System.out.println(ex.getMessage()+"==="+ex.toString());//throw new RuntimeException("接收错误");//=================
}
finally
{
socket.close();
}
}
}
|
|