UDP传输long类型的数

来源:互联网 发布:上海新房成交数据 编辑:程序博客网 时间:2024/05/30 23:43

UDP协议传输long类型的数

//UDP的一端

import java.io.*;import java.net.*;public class TestUDPServer {    public static void main(String[] args) {        try {            byte[] buf = new byte[1024];            DatagramSocket ds = new DatagramSocket(9999);            DatagramPacket dp = new DatagramPacket(buf, 0, buf.length);            while(true) {                ds.receive(dp);                ByteArrayInputStream bis = new ByteArrayInputStream(buf);                DataInputStream dis = new DataInputStream(bis);                System.out.println(dis.readLong());            }        } catch (SocketException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }}

//UDP另一端

import java.io.*;import java.net.*;public class TestUDPClient {    public static void main(String[] args) {        try {            //byte[] buf = (new String("hello")).getBytes();            long n = 1000L;            ByteArrayOutputStream baos = new ByteArrayOutputStream();            DataOutputStream dos = new DataOutputStream(baos);            dos.writeLong(n);            byte[] buf = baos.toByteArray();            DatagramSocket ds = new DatagramSocket(8888);            DatagramPacket dp = new DatagramPacket(buf, buf.length,                                                 new InetSocketAddres("127.0.0.1", 9999));            ds.send(dp);            ds.close();        } catch (SocketException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }}
0 0