码迷,mamicode.com
首页 > 编程语言 > 详细

java,UDP协议简单实现

时间:2015-03-02 16:18:33      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

//UDP协议简单实现-----Server
package
UDP; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.nio.ByteBuffer; public class UdpServer implements Runnable { private int port; public UdpServer(int port) { this.port = port; } public void run() { try { // listening at port for udp request DatagramSocket server = new DatagramSocket(new InetSocketAddress(port)); byte[] bs = new byte[4]; ByteBuffer bbuf = null; DatagramPacket data = new DatagramPacket(bs, bs.length); server.setSoTimeout(1000 * 10); // set timeout while (true) { // 一直监听 server.receive(data); bbuf = ByteBuffer.wrap(bs, 0, 4); String s = "receive " + data.getData().length + " byte data,value: " + bbuf.getInt(); System.out.println(s); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new Thread(new UdpServer(11111)).start(); } }

 

//客户端实现;

package UDP;

    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetSocketAddress;


    public class UdpClient implements Runnable {
        private int port;

        public UdpClient(int port) {
            this.port = port;
        }

        public void run() {
            try {
                DatagramSocket client = new DatagramSocket();
                byte[] bs = new byte[4];
                InetSocketAddress isa = new InetSocketAddress("localhost", port);
                DatagramPacket data = new DatagramPacket(bs, bs.length);
                data.setSocketAddress(isa);
                for (int i = 0; i < 10; i++) {
                    data.setData(int2bytes(i));
                    client.send(data);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        static byte[] int2bytes(int num) {
            byte[] b = new byte[4];
            for (int i = 0; i < 4; i++) {
                b[i] = (byte) (num >>> (24 - i * 8));
            }
            return b;
        }
    }

 

 

//测试代码;

package UDP;

public class Test {
    public static void main(String[] args) throws InterruptedException {
        int port = 11111;
        try{
            new Thread(new UdpServer(port)).start();
            new Thread(new UdpClient(port)).start();
        }catch(Exception e){
            //e.printStackTrace();
        }
    }
}

 

java,UDP协议简单实现

标签:

原文地址:http://www.cnblogs.com/qianyukun/p/4308785.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!