Capstone/2019-1 Capstone

⑦ TCP 통신

Jeongmin Lee 2019. 6. 21. 18:00

TCP 통신


Client가 Server로 txt파일과 동영상을 보냅니다.

Server는 Python으로 Client는 JAVA로 작성했습니다.

TCP통신  Client_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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package com.example.ijeongmin.tcp2;
 
import android.os.Build;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.mbms.StreamingServiceInfo;
import android.util.Log;
import android.view.View;
import android.os.AsyncTask;
import android.widget.Button;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
 
public class MainActivity extends AppCompatActivity {
    TCP_Client tc;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        if(Build.VERSION.SDK_INT>22){
            requestPermissions(new String[] {"android.permission.READ_EXTERNAL_STORAGE"}, 1);
        }
        Button But = (Button)findViewById(R.id.Button01);
        But.setOnClickListener(new onClick());
    }
    public class onClick implements View.OnClickListener{
        public void onClick(View v){
            tc = new TCP_Client();
            tc.execute(this);
        }
    }
 
    public static class TCP_Client extends AsyncTask {
        protected static String SERV_IP = "123.456.789.10"//서버의 ip주소를 작성하면 됩니다.
        protected static int PORT = 1234//서버의 Port번호를 작성하면 됩니다.
 
        @Override
        protected Object doInBackground(Object... params) {
 
            try {
                Log.d("TCP""server connecting");
                InetAddress serverAddr = InetAddress.getByName(SERV_IP);
                Socket sock = new Socket(serverAddr, PORT);
 
                try{
                    System.out.println("데이터찾는중");
 
                    File file = new File(Environment.getExternalStorageDirectory().getPath()+"/MediaManagerDemo/""capstonetest.txt"); //읽을 파일 경로 적어 주시면 됩니다.
 
                    DataInputStream dis = new DataInputStream(new FileInputStream(file)); 
                    DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
 
                    long fileSize = file.length();
                    byte[] buf = new byte[1024];
 
                    long totalReadBytes = 0;
                    int readBytes;
                    System.out.println("데이터찾기 끝");
 
                    while ((readBytes = dis.read(buf)) > 0) { //길이 정해주고 서버로 보냅니다.
                        System.out.println("while");
                        dos.write(buf, 0, readBytes);
                        totalReadBytes += readBytes;
                    }
 
                    System.out.println("데이터보내기 끝 직전");
                    dos.close();
                    System.out.println("데이터끝");
 
                } catch(IOException e){
                    Log.d("TCP""don't send message");
                    e.printStackTrace();
                }
 
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch(IOException    e){
                e.printStackTrace();
            }
            return null;
        }
    }
}
 
cs



TCP통신  Server_Python

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
from socket import *
import socket
import os
import time
import sys
import detector
import vvv
 
# 이미지 파일 저장경로
src = "./temp"
 
 
def fileName():
    dte = time.localtime()
    Year = dte.tm_year
    Mon = dte.tm_mon
    Day = dte.tm_mday
    WDay = dte.tm_wday
    Hour = dte.tm_hour
    Min = dte.tm_min
    Sec = dte.tm_sec
    imgFileName = src + str(Year) + '_' + str(Mon) + '_' + str(Day) + '_' + str(Hour) + '_' + str(Min) + '_' + str(Sec) 
    return imgFileName
 
 
# 서버 소켓 오픈
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((""1234))
server_socket.listen(5)
 
file_recive_cnt = 0
 
print("TCPServer Waiting for client on port 7163")
 
while True:
 
    # 클라이언트 요청 대기중 .
    client_socket, address = server_socket.accept()
    # 연결 요청 성공
    print("I got a connection from ", address)
 
    data = None
 
    # Data 수신
    while True:
        rev_path = './temp/'
        rev_flist = os.listdir(rec_path)
        rev_flist.remove(".DS_Store")
        if(file_recive_cnt > 2):
            for fname in rev_flist:
                os.sys("rm " + fname)
            file_recive_cnt = 0
 
        img_data = client_socket.recv(1024)
        data = img_data
        if img_data:
            while img_data:
                print("recving Img...")
                img_data = client_socket.recv(1024)
                data += img_data
            else:
                break
 
    # 받은 데이터 저장
        img_fileName = fileName()
        print(img_fileName)
 
        if file_recive_cnt == 0:
            img_fileName = img_fileName+".mp4"
        elif file_recive_cnt == 1:
            img_fileName = img_fileName+'.txt'
 
        img_file = open(img_fileName, "wb")
 
        print("finish img recv")
        print(sys.getsizeof(data))
 
        img_file.write(data)
        img_file.close()
        client_socket.close()
 
        print("Finish ")
        file_recive_cnt+=1
 
        vvv.capture() # 비디오 캡쳐.py
        detecor.detection() # darknet.py
 
 
print("SOCKET closed... END")
cs


반응형