首页 > 其他 > 详细

UDP server & client

时间:2016-02-02 14:46:40      阅读:148      评论:0      收藏:0      [点我收藏+]

 

Server:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPServerTest {

    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket(9954);

        byte[] data = new byte[512];
        DatagramPacket dp = new DatagramPacket(data, data.length);

        while (true) {
            ds.receive(dp);

            System.out.println("receive:");
            System.out.println(dp.getSocketAddress());
            System.out.println(new String(data, "UTF-8"));

            //response
            String st = "qnmlgb~hi!";
            byte[] bytes = st.getBytes();
            DatagramPacket response = new DatagramPacket(bytes, bytes.length,
                dp.getSocketAddress());
            ds.send(response);
        }
    }

}

 

Client:

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

public class UDPClientTest {

    public static InetSocketAddress localServer = new InetSocketAddress("127.0.0.1", 9954);

    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket();
        String st = "loull~hi!";
        byte[] data = st.getBytes();
        DatagramPacket dp = new DatagramPacket(data, data.length, localServer);
        ds.send(dp);

        int localPort = ds.getLocalPort();
        System.out.println("localport:" + localPort);

        byte[] buf = new byte[512];
        DatagramPacket receive = new DatagramPacket(buf, buf.length);
        ds.receive(receive);
        String response = new String(receive.getData(), 0, receive.getLength());
        System.out.println("response:" + response);
    }

}

 

UDP server & client

原文:http://www.cnblogs.com/549294286/p/5177322.html

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