자바 UDP 일대일 파일 전송

2187 단어 자바네트워크UDP
자바 기반 네트워크 프로 그래 밍 을 배 웠 습 니 다. 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();
			}
		}
	}

}

좋은 웹페이지 즐겨찾기