首页 > 其他 > 详细

UDP传输数据

时间:2015-06-18 23:43:48      阅读:283      评论:0      收藏:0      [点我收藏+]

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

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传输数据

原文:http://www.cnblogs.com/jamsbwo/p/4587092.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!