a1670131049 2019-03-19 12:00 采纳率: 50%
浏览 300
已采纳

Java UD协议,聊天程序

问题:
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)

  • 写回答

1条回答 默认 最新

  • 毕小宝 博客专家认证 2019-03-19 13:57
    关注

    是不是服务端重复运行了?
    JieShou.class是死循环,只需要运行一次就可以了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波