자바 UDP 일대일 파일 전송
UDP 는 신뢰 할 수 있 는 전송 방식 이 아 닙 니 다. 바이트 시퀀스 가 검증 되 지 않 았 기 때문에 파일 을 전송 할 때 오류 가 발생 하 는 것 도 불가피 합 니 다. txt, doc, jpg 자체 가 오류 가 발생 하 더 라 도 열 리 는 데 영향 을 주지 않 습 니 다. 기껏해야 개별 문자 나 개별 픽 셀 오류 가 발생 하면 전체 에 영향 을 주지 않 습 니 다. exe 는 cpu 의 명령 실행 시퀀스 입 니 다. 하 나 를 잘못 하면 프로그램 이 실 행 될 수 없습니다.
파일 전송 에 대해 서 는 tcp, 점 대 점 전송 을 권장 합 니 다.
다음은 제 코드 입 니 다. 여러분 께 쓰 시기 바 랍 니 다.
고객 센터:
서버:
import java.io.FileInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* udp ,
* @author jun
* @date: 2012-11-15
*/
public class Client {
public static void main(String[] args) {
FileInputStream fis = null; //file
DatagramSocket sendSocket= null; //socket
DatagramPacket sendPacket =null; //send packet
DatagramPacket getPacket = null; //get packet
InetAddress ip = null; //ip
try {
sendSocket = new DatagramSocket();
int port = 8888;
ip = InetAddress.getLocalHost();
fis = new FileInputStream("E:\\test.mp3");
byte[] buf =new byte[1024];
int i;
while((i = fis.read(buf, 0, 1024) )==1024){
System.out.println(i);
sendPacket = new DatagramPacket(buf, buf.length, ip, port);
sendSocket.send(sendPacket);
Thread.sleep(1); //
}
System.out.println(i);
sendPacket = new DatagramPacket(buf, 0,i, ip, port);
sendSocket.send(sendPacket);
Thread.sleep(1); //
System.out.println("client send done.");
byte[] getBuf = new byte[1024];
getPacket = new DatagramPacket(getBuf, getBuf.length);
sendSocket.receive(getPacket);
//get feedback message
String backMes = new String(getBuf, 0, getPacket.getLength());
System.out.println("feefBack:"+backMes);
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(fis !=null){
fis.close();
}
if(sendSocket != null){
sendSocket.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.