java6.02学习笔记UDPserver

简单的udp传输程序。

import java.net.*;
import java.io.*;

public class UDPServer {
    public static void main(String[] args) throws Exception {
    //1创建一个byte数组存储输入的信息
        byte[] buf = new byte[1024];
        //2将输入的信息数组存储到包中,使用了DatagramSocket的构造方法。
        DatagramPacket dp = new DatagramPacket(buf,buf.length);
        //设置收信息的端口
        DatagramSocket ds = new DatagramSocket(8888);

        while(true) {
        //信息一旦传入就会存储到包中,使用receive()读取包。使用DatagramSocket中的getLength()方法获取接收到信息的长度。
            ds.receive(dp);
            System.out.println(new String(buf,0,dp.getLength()));
        }
    }
}

UDPCilent

import java.net.*;

public class UDPCilent {
    public static void main(String[] args) throws Exception {
    //将信息存储在数组中,getBytes方法可以将字符串转换成字符序列并存储到一个数组中。
        byte[] buf = (new String(String.valueOf(2365L)).getBytes());
        //将数据打包。
        DatagramPacket dp = new DatagramPacket(buf,buf.length,new InetSocketAddress("192.168.1.100",8888));
        //设置Cilent端口
        DatagramSocket ds = new DatagramSocket(6666);
        //发送数据。
        ds.send(dp);
        ds.close();
    }
}

将一个long型数传输,经常用到,使用了io流的相关知识。

import java.net.*;
import java.io.*;

public class UDPServer {
    public static void main(String[] args) throws Exception {
        byte[] buf = new byte[1024];

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

        DatagramSocket ds = new DatagramSocket(8888);

        while(true) {
            ds.receive(dp);
            //将字节数组存储到流中的字节数组中
            ByteArrayInputStream bas = new ByteArrayInputStream(buf);
            DataInputStream dis = new DataInputStream(bas);
            //调用readLlong方法读出数组。
            System.out.println(dis.readLong());
            //System.out.println(new String(buf,0,dp.getLength()));
        }
    }
}

客户端

import java.net.*;
import java.io.*;
public class UDPCilent {
    public static void main(String[] args) throws Exception {
        long n = 54651L;
        //为字节数组建立管道
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(bos);
        //将字节数组写入流中,存储在一个字节数组中
        dos.writeLong(n);
        //将字节数组使用toVyteArray()方法恢复。
        byte[] buf = bos.toByteArray();


        System.out.println(buf.length);


        //byte[] buf = (new String(String.valueOf(2388888865L)).getBytes());
        DatagramPacket dp = new DatagramPacket(buf,buf.length,new InetSocketAddress("192.168.1.100",8888));

        DatagramSocket ds = new DatagramSocket(6666);
        ds.send(dp);
        ds.close();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值