问题:
First.class 是发送端,从键盘录入,发送内容到 Jieshou.class ,键入over结束发送。
Jieshou.class 是接受端。
我的目的是从发送端不断键入数据到接收端,通过自定义结束标记 “over”结束程序。
问题是,只从发送端输入了一次数据,接收端接收了,之后就抛出异常。
请教该如何解决
public class First {
public static void main(String[] arg) throws IOException{
System.out.println("发送端启动。。");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String line=null;
DatagramSocket ds=new DatagramSocket(8888);
while((line=br.readLine())!=null){
byte[] buf=line.getBytes();
DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.189.1"),9999);
ds.send(dp);
if("over".equals(line))
break;
}
ds.close();
}
}
public class Jieshou {
public static void main(String[] args) throws IOException{
System.out.println("接受端启动。。");
while(true){
DatagramSocket ds=new DatagramSocket(9999);
byte[] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf,buf.length);
ds.receive(dp);
String t=new String(dp.getData(),0,dp.getLength());
System.out.println(t+".."+dp.getAddress().getHostAddress()+":"+dp.getPort());
}
}
}
异常代码:
Exception in thread "main" java.net.BindException: Address already in use: Cannot bind
at java.net.DualStackPlainDatagramSocketImpl.socketBind(Native Method)
at java.net.DualStackPlainDatagramSocketImpl.bind0(Unknown Source)
at java.net.AbstractPlainDatagramSocketImpl.bind(Unknown Source)
at java.net.DatagramSocket.bind(Unknown Source)
at java.net.DatagramSocket.<init>(Unknown Source)
at java.net.DatagramSocket.<init>(Unknown Source)
at java.net.DatagramSocket.<init>(Unknown Source)
at Test.Jieshou.main(Jieshou.java:11)