UDP通讯demo

要求:使得接受者可以连续接收发送者发送的数据
发送的数据是可变的,如可以从控制台上输入;

public void sendSocket() throws IOException {
        DatagramSocket socket = new DatagramSocket(10001);
        while (true) {
            byte[] bs = new byte[1024];
            DatagramPacket pack = new DatagramPacket(bs, bs.length);
            socket.receive(pack);
            InetAddress adress = pack.getAddress();
            byte[] b = pack.getData();
            int port = pack.getPort();
            System.out.print(adress + "  ");
            System.out.print(port + "  ");
            System.out.println(new String(b, 0, b.length));
        }

 }
//键盘接收数据的发送端
public
static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = null; DatagramSocket socket = new DatagramSocket(); DatagramPacket pack = null; byte[] bs = null; while ((str = br.readLine()) != null) { if (str.equals("finish")) break; bs = str.getBytes(); pack = new DatagramPacket(bs, bs.length, InetAddress.getByName("127.0.0.1"), 10001); socket.send(pack); } socket.close(); }

 

posted @ 2020-07-30 11:13  达摩院的BLOG  阅读(239)  评论(0编辑  收藏  举报