- 前段时间,结合Andriod手机做了UDP的C/S通信,简单传送字符串,还有自定义UDP通信协议,作了传送火车票的信息,并进行反馈。
UDP通信:理解几个名词
1.DatagramSocket:用来发送和接收数据包的套接字(Socket),数据报套接字是包投递服务的发送或接收点。每个在数据报套接字上发送或接收的包都是单独编址和路由的。从一台机器发送到另一台机器的多个包可能选择不同的路由,也可能按不同的顺序到达。
2.DatagramPacket:数据报包,用来实现无连接包投递服务。每条报文仅根据该包中包含的信息从一台机器路由到另一台机器。从一台机器发送到另一台机器的多个包可能选择不同的路由,也可能按不同的顺序到达。不对包投递做出保证。
3.InetAddress:互联网协议 (IP) 地址。若你想知道自己电脑的ip,你可以打开命令提示符,然后输入ipconfig指令即可。
4.port :端口号
我有个很通俗的理解,每个人都有自己的家,家里有很多个门,那么当一个人要寄东西给另一个人时,就会给物品打包,打包之后从家里的一个门递出去给快递员,快递员看了地址之后就送到你指定的地址,指定的那个门给对方接收。
以上我做的东西都是发送一个包给对方,对方接受一个包,而如果你要寄的东西很多很多,一个人都不可以送得完,那就得分几个包打包,分几个人发送。
比如:当你发送一个很大的文件的时候,由于文件内容过大,我们就可以拆分成多个数据包发送。
下面我们进入今天正题,实现文件的传输。
- 首先需要读取到文件;
- 然后对文件内容转化成byte数组,定义每个包的所传送的byte数组的大小,我定义的就是1024长度的。
- 然后一边拆包一边发送;
- 接收者就用同一个文件类型存储接收的内容,一边接收一边解析出来;
- 最后刷新自己的接收的项目,就会发现新生成了一个文件。
public class SendFile extends Thread{
private DatagramSocket ds;
public static void main(String[] args) throws IOException {
File f=new File("D://workspace//chan//src//com//chan//UDPSendFile0226//压缩.txt");
if(f.getName().endsWith(".txt"))
send_txt(f);
else if(f.getName().endsWith(".jpg"))
send_jpg(f);
else
System.out.println("找不到文件");
}
private static void send_txt(File f) throws IOException {
FileInputStream fis=new FileInputStream(f);
byte[] bs=new byte[65536];
int length=fis.read(bs);
byte[] b=new byte[length];
System.arraycopy(bs, 0, b, 0, length);
DatagramSocket ds=new DatagramSocket();
int cont=0;
int l=b.length;
while(l>0)
{
byte[] y=new byte[1024];
int sub=1024-l;
if(sub<0)
System.arraycopy(b, cont*1024, y, 0, y.length);
else
System.arraycopy(b, cont*1024, y, 0, l);
cont++;
l=l-1024;
DatagramPacket dp=null;
dp=new DatagramPacket(y,1024, InetAddress.getByName("192.168.31.57"), 9080);
ds.send(dp);
}
ds.close();
fis.close();
}
private static void send_jpg(File f) throws IOException {
}
}
接收
public class Recive extends Thread{
public static void main(String[] args) throws IOException {
Recive receive=new Recive();
receive.start();
}
public void run()
{
try {
FileOutputStream fos=new FileOutputStream(new File("D://workspace//chan//src//com//chan//UDPReciverFile0226//解压.txt"));
DatagramSocket ds=new DatagramSocket(9080);
while(true)
{
byte[] receive=new byte[1024];
DatagramPacket dp=new DatagramPacket(receive, receive.length);
ds.receive(dp);
fos.write(receive);
fos.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}