简单的UDP 消息的传递以及URL文件下载

特别注意:int a = s.getBytes().length;     是获取字节数长度,不是字符串长度,否则汉字出现乱码    

发送端:



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


public class Send {


public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket();
// File f = new File("D:/ccc.txt");
// FileInputStream fi = new FileInputStream(f);
// BufferedReader br=new BufferedReader(new InputStreamReader(fi));
// String s1 = "";
// while ((s1 = br.readLine()) != null) {
// int a = s1.getBytes().length;
// int count = a / 30;
// int left = a % 30;
// for (int i = 0; i < count; i++) {
// DatagramPacket dp = new DatagramPacket(s1.getBytes(), i * 30, 30,
// InetAddress.getByName("localhost"), 6668);
// ds.send(dp);
// }
// DatagramPacket dp = new DatagramPacket(s1.getBytes(), count * 30, left,
// InetAddress.getByName("localhost"), 6668);
// ds.send(dp);
// }


String s = "hello world,how are you ,i am fine, do dou want to go to the zoo?,我晕";
int a = s.getBytes().length;
int count = a / 30;
int left = a % 30;
for (int i = 0; i < count; i++) {
DatagramPacket dp = new DatagramPacket(s.getBytes(), i * 30, 30, InetAddress.getByName("localhost"),
6668);
ds.send(dp);
}
DatagramPacket dp = new DatagramPacket(s.getBytes(), count * 30, left, InetAddress.getByName("localhost"),
6668);
ds.send(dp);


} catch (Exception e) {
e.printStackTrace();
}


}

}





接收端:

import java.net.*;


public class Save {


public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket(6668);
byte[] b = new byte[30];
while (true) {
DatagramPacket dp = new DatagramPacket(b, b.length);
ds.receive(dp);
byte[] data = dp.getData();
String string = new String(data, 0, dp.getLength());
System.out.println(string);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}





URL文件下载:

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;


public class Test {


public static void main(String[] args) {
BufferedInputStream bi = null;
BufferedOutputStream bo = null;
File f = new File("http://img06.tooopen.com/images/20160712/tooopen_sy_170083325566.jpg");
File file = new File("E:/", f.getName());
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
URL url = new URL("http://img06.tooopen.com/images/20160712/tooopen_sy_170083325566.jpg");
InputStream in = url.openStream();
bi = new BufferedInputStream(in);
FileOutputStream fo = new FileOutputStream(file);
bo = new BufferedOutputStream(fo);
int a = -1;
while ((a = bi.read()) != -1) {
bo.write(a);
}


} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bi.close();
bo.close();
} catch (IOException e) {
e.printStackTrace();
}


}


}


}




1、不可靠的、效率高、数据报(数据打成一个小包一个小包地往外发)、非连接。
2、UDP是非连接的,因此严格来说并不区分服务器端和客户端。
3、UDP通信过程:UDP都是通过字节数组进行对话的。
     "服务器"端:接数据
          (1)新建字节数组,用来接收对方发过来的数据
               byte buf[] = new byte[1024];
          (2)创建数据包Socket
               DatagramSocket ds = new DatagramSocket(5678);//端口号5678是udp的5678,TCP还有一个端口5678
          (3)新建包裹DatagramPacket ,包裹把byte字节数组都占满了,第二个参数表示包裹在数组中占的长度。当调用receive()方法接收数据时,将接收到的内容存放到字节数组buf中。
               DatagramPacket  dp = new DatagramPacket (buf, buf.length);
          (4)接收对方发来的数据,有人发数据,就把数据放在包袱里,receive也是阻塞式的方法,如果没有人发数据,就一直等着。
               ds.receive(dp);
               System.out.println(new String(buf,0,dp.getLength()));//把包袱里有的内容转换成字符串输出String(buf,0,dp.getLength())表示通过数组的一部分构建字符串。dp.getLength() 表示字节数组里到底占用了多少空间。
                ds.close();
     “客户”端:发数据
            (1) 将要发送的内容转换成字节数组
               byte[] buf = (new String("Hello")).getBytes();
            (2)创建包裹,并把字节数组放进去,InetSocketAddress是SocketAddress的子类表示Ip地址。
               DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress("127.0.0.1", 5678));
            (3)创建数据包Socket
               DatagramSocket ds = new DatagramSocket(9999);//9999是客户端的端口
            (4)发送信息
               ds.sent(dp);
               ds.close();
          以上例子中传的是String字符串类型的消息;如果要传Long类型的消息,需要通过ByteArrayOutputStream来传消息;服务器端接收时用ByteArrayInputStream。
          客户端:long n = 1000L;
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          DataOutputStream dos = new DataOutputStream(baos );//为了写入long型的数据,采用DataOutputStream处理流
          dos.writeLong(n);//向字节数组输出流中写数据
          byte[]  buf = baos.toByteArray();//将流中的内容转换成字节数组,进而创建DatagramPacket,并用UDP的 DatagramSocket发出消息。
          接下来与上面的例子一致。
          服务器端:
          ds.receive(dp);
          ByteArrayInputStream bais = new ByteArrayInputStream(buf);
          DataInputStream dis = new DataInputStream(bais);
          System.out.println(dis.readLong());
注意:在UDP中用的最多的流就是ByteArrayOutputStream、DataOutputStream和ByteArrayInputStream、DataInputStream

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值