UDP传输数据

这里只设置了一个输入端和一个接收端,由于没有设置线程,只能单方向传输数据

1.输入端程序

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;



public class 输入端 {

    public static void main(String[] args) throws IOException {

        System.out.println("UDP OUTPUT RUN");

        System.out.println("传输内容('over'或'exit'退出)):");

        BufferedReader buffer = new BufferedReader(new InputStreamReader(

                System.in));

        String line = null;

        DatagramSocket mail_to = new DatagramSocket();

        while ((line = buffer.readLine()) != null) {

            if (line.compareToIgnoreCase("exit") == 0

                    || line.compareToIgnoreCase("over") == 0)

                break;

            byte[] buf = line.getBytes();

            // System.out.println(InetAddress.getByName("172.16.149.49"));

            DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress

                    .getByName("172.31.42.5"), 10000);

            mail_to.send(dp);

        }

        mail_to.close();

    }

}
View Code

2.接收端程序

import java.io.IOException;

import java.net.DatagramPacket;

import java.net.DatagramSocket;



public class 接收端 {

    public static void main(String[] args) throws IOException {

        System.out.println("UDP INPUT RUN");

        byte[] buf = new byte[1024];

        DatagramSocket mail_from = new DatagramSocket(10000);

        while (true) {

            DatagramPacket dp = new DatagramPacket(buf, buf.length);

            mail_from.receive(dp);

            String add = dp.getAddress().getHostAddress();

            int port = dp.getPort();

            System.out.print("收到数据:\n物理地址:" + add + ";\n" + "端口:" + port

                    + "\n内容:");

            String message = new String(dp.getData(), 0, dp.getLength());

            System.out.println(message);

        }

    }

}
View Code

你可能感兴趣的:(UDP)