日期:2014-05-20 浏览次数:20885 次
import java.awt.Button; import java.awt.Frame; import java.awt.TextArea; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; class PC100 extends Frame implements Runnable,ActionListener{ TextField out=new TextField("send to pc2"); TextArea in=new TextArea(); Button b=new Button("send"); PC100(){ super("This is pc1"); setSize(200,200); setVisible(true); b.addActionListener(this); add(out,"South"); add(in,"Center"); add(b,"North"); Thread t=new Thread(this); t.start(); this.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); } @Override public void run() { // TODO Auto-generated method stub DatagramPacket pack=null; DatagramSocket mail=null; byte data[]=new byte[8192]; try{ pack=new DatagramPacket(data,data.length); mail=new DatagramSocket(9998);//////////////////////// }catch(Exception e){ e.printStackTrace(); System.out.println("run01 error!"); } while(true){ if(mail==null) break; else try{ mail.receive(pack); //////////异常。。。。。 int length=pack.getLength(); InetAddress add=pack.getAddress(); int port=pack.getPort(); String msg=new String(pack.getData(),0,length); in.append("length:"+length+"\n"); in.append("From:"+add+"port:"+port+"\n"); in.append("data:"+msg+"\n"); }catch(Exception e){ e.printStackTrace(); in.append("run22\n");break; } } } @Override public void actionPerformed(ActionEvent event) { // TODO Auto-generated method stub byte buffer[]=out.getText().trim().getBytes(); try{ InetAddress add=InetAddress.getByName("127.0.0.1"); ////////////////////// DatagramPacket data=new DatagramPacket(buffer,buffer.length,add,9998); DatagramSocket mail=new DatagramSocket(); in.append("IP:"+data.getAddress()+"\n"); in.append("port:"+data.getPort()+"\n"); in.append("length:"+data.getLength()+"\n"); mail.send(data); }catch(Exception e){System.out.println("send error!");} } } public class PC1{ public static void main(String args[]){ PC100 pc10=new PC100(); pc10.validate(); } }
java.net.SocketException: Socket closed at java.net.PlainDatagramSocketImpl.receive0(Native Method) at java.net.PlainDatagramSocketImpl.receive(PlainDatagramSocketImpl.java:136) at java.net.DatagramSocket.receive(DatagramSocket.java:712) at PC100.run(PC1.java:56) at java.lang.Thread.run(Thread.java:619)