본문 바로가기

Java SE/Socket File Transfer

File Transfer in Java Socket

서버와 클라이언트 소켓간의 이미지 파일 전달 예제

아래의 내용은 클라이언트가 서버에 접속하는 즉시 서버는 이미지 데이터를 클라이언트에게 전송해주는 예제이다


Server.java

/*

 * To change this license header, choose License Headers in Project Properties.

 * To change this template file, choose Tools | Templates

 * and open the template in the editor.

 */


package org.kdea.filetransfer;


import java.io.*;

import java.net.*;


/**

 *

 * @author duniv6-000

 */

public class Server 

{

    public static void main(String[] args) 

    {

        init();

    }

    

    private static void init()

    {

        ServerSocket ss = null;

        try {

            while(true) {

                ss = new ServerSocket(1234);

                System.out.println("서버 대기중....");

                Socket socket = ss.accept();

                OutputStream os = socket.getOutputStream();

                FileInputStream fin = new FileInputStream("d:/test/sample.jpg");

                byte[] buf = new byte[1024];

                int read = 0;

                while((read=fin.read(buf, 0, buf.length))!=-1)

                {

                    os.write(buf, 0, read);

                }

                fin.close();

                os.close();

                System.out.println("파일 전송완료");

            }

        } catch (IOException ex) {

            ex.printStackTrace();

            //Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);

        }

    }

}



Client.java
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.kdea.filetransfer;

import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author duniv6-000
 */
public class Client 
{
    public static void main(String[] args)
    {
        Socket socket = null;
        try {
            socket = new Socket("localhost", 1234);
            InputStream is = socket.getInputStream();
            byte[] buf = new byte[1024];
            int read = 0;
            
            FileOutputStream fout = new FileOutputStream("d:/test/svrTrans.jpg");
            
            while((read=is.read(buf, 0, buf.length))!=-1)
            {
                fout.write(buf, 0, buf.length);
            }
            is.close();
            fout.close();
            System.out.println("파일 수신 및 저장 성공");
        } catch (Exception ex) {
            ex.printStackTrace();
            //Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
}