2017년 4월 15일 토요일

#Python + #Java socket. 파이썬+자바 소켓 파일 전송(이미지 전송)

-----------------------------------------------------------------------------------------------------------
imageServer.py
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/usr/bin/env python
# -*- coding:utf8 -*-
import socket
import os
import sys
HOST = 'localhost'
PORT = 5000
ADDR = (HOST,PORT)
BUFSIZE = 4096
videofile = "../Pictures/desert.png"
serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
filename = "i.png"
#Bind Socket
serv.bind(ADDR)
serv.listen(5)
conn, addr = serv.accept()
print 'client connected ... ', addr
#Open the file
#Read and then Send to Client
f=open(filename,'rb')# open file as binary
data=f.read()
print data,',,,'
exx=conn.sendall(data)
print exx,'...'
f.flush()
f.close()
#Close the Socket 
print 'finished writing file'
conn.close()
serv.close()
cs

-----------------------------------------------------------------------------------------------------------
imageClient.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package sending;
/**
 * @author haei
 */
import java.io.*;
import java.net.Socket;
public class FileClient {
  
    private Socket s;
  
    public FileClient(String host, int port) {
        try {
            s = new Socket(host, port);
                        saveFile(s);
        } catch (Exception e) {
            e.printStackTrace();
        }      
    }
      
        private void saveFile(Socket clientSock) throws IOException
        {
                InputStream in = clientSock.getInputStream();
                //바이트 단위로 데이터를 읽는다, 외부로 부터 읽어들이는 역할을 담당
                BufferedInputStream bis = new BufferedInputStream(in);
                //파일을 읽는 경우라면,BufferedReader보다 BufferedInputStream이 더 적절하다.
                FileOutputStream fos = new FileOutputStream("testfile.png");
                //파일을 열어서 어떤식으로 저장할지 알려준다. FileOutputStream을 쓰면 들어오는 파일과 일치하게 파일을 작성해줄 수 있는 장점이 있다.
               
                int ch;
                while ( (ch = bis.read()) != -1) {
                    fos.write(ch);
                    //열린 파일시스템에 BufferedInputStream으로 외부로 부터 읽어들여온 파일을 FileOutputStream에 바로 써준다.
                }
        fos.close();
        in.close();
    }
  
    public static void main(String[] args) {
        FileClient fc = new FileClient("localhost"5000);
    }
}
cs

----------------------------------------------------------------------------------------------------------

이 소스를 만들어내는데 많이 헤매서 생각보다 오래걸렸다.
어떻게 보면 간단한 생각이지만, 아직 내가 많이 부족한 관계로 이 간단한 소켓하나 작성하지 못하는 수준이였다.. 결국 물어물어서 해결한 문제지만, 해결이 되고나니 뿌듯하다.

파이썬-파이썬 /자바-자바 간의 소켓문제는 많이 존재하지만, 다른 언어사이의 예제가 생각보다 찾기가 어려웠다.

파이썬Server 와 자바Client간의 파일 전송을 작성한 예제이다.
처음에는 자바에서 인코딩문제인가?를 생각해서 Binary로 처리해야되나?라는 생각을 하게되었고 f=open(filename,'rb') 파일을 "ReadBinary"하고 있다.

두번째로는 BufferedInputStream이다. 자바에는 많은 처리 함수들이 존재하기 때문에 각자 어떤때에 쓰이는지 정리, 공부해두면 좋을 것같다는 생각이 들었다.

파일이 필요한 사람이 있을까봐 파일도 첨부 해 놓겠다.
java python

댓글 없음:

댓글 쓰기