资源简介
socket使用udp方式发送和接收图片,包含图片测试
代码片段和文件信息
package com.udpimg;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UDPFileReceive {
private int port = 1220;
private DatagramSocket socket;
public UDPFileReceive() throws SocketException{
socket = new DatagramSocket(port);
socket.setSoTimeout(4000);
}
public void reciveData() throws FileNotFoundException{
File newfile = new File(“D:\\2.jpg“);
byte[] buf = new byte[8192];
FileOutputStream fos = new FileOutputStream(newfile);
while(true){
DatagramPacket packet = new DatagramPacket(buf 8192);
try{
socket.receive(packet);
fos.write(packet.getData() 0 packet.getLength());
}catch(Exception e){
try {
System.out.println(“传输结束“);
socket.close();
fos.flush();
fos.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
}
}
}
public static void main(String[] args) throws FileNotFoundException SocketException {
new UDPFileReceive().reciveData();
}
}
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 4755 2014-10-15 17:42 udp\2.jpg
文件 1231 2014-10-15 17:44 udp\UDPFileReceive.java
文件 1050 2014-10-15 17:43 udp\UDPFileServer.java
目录 0 2015-01-09 11:04 udp
----------- --------- ---------- ----- ----
7036 4
评论
共有 条评论