반응형

자바(JAVA) 실습 - TCP 전문 통신 (fixed length) - readInt, writeInt 활용 (2)

 

환경 OpenJDK 1.8

 

FixedData

1. Client가 전송하는 전문의 형태를 지정

2. 배열로 각 전문의 키와 값을 지정

3. 기타 정보 저장

 

ReceivedLinkedMapData

1. 전문을 LinkedMap 형태로 저장

2. 전문의 항목을 키와 값으로 저장

 

ReceivedMapDataGlobal

1. LinkedMap 형태의 전체 전문을 키(ex. global id)에 매핑하여 저장

 

Server

1. 전문의 첫 4byte에 전문의 전체 길이 읽기 (readInt)

2. 전문 읽기 (read)

3. 전문 내용 확인 및 특정 키에 저장

4. 전문 확인 후 조합한 메세지를 client에게 전송 (writeInt, write)

5. 전송 후 대기

 

Client

1. 전문의 첫 4byte에 전문의 전체 길이 (writeInt)

2. 메세지 전송 (write)

3. 전문을 Server에 전송

4. 응답 메세지 읽기 (readInt, read)

5. 메세지 표시 후 종료

 

Global ID를 키로 전문데이터를 매핑하여 저장

현재는 echo 서버를 작성하는데 주력

저장한 데이터 활용은 요구조건에 따라 처리 예정

 

Server - readInt, writeInt 활용

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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.LinkedHashMap;
 
public class TcpServerExample extends FixedData {
 
    public static void main(String[] args) {
        new TcpServerExample(tcpServerPort);
    }
 
    public static int tcpServerPort = 9999;
 
    public class Server extends Thread {
        private Socket socket;
 
        public Server(Socket socket) {
            this.socket = socket;
        }
 
        public void run() {
            try {
                while (true) {
                    OutputStream os = this.socket.getOutputStream();
                    DataOutputStream dos = new DataOutputStream(os);
 
                    InputStream is = this.socket.getInputStream();
                    DataInputStream dis = new DataInputStream(is);
 
                    // read int
                    int recieveLength = dis.readInt();
 
                    // receive bytes
                    byte receiveByte[] = new byte[recieveLength];
                    dis.readFully(receiveByte, 0, recieveLength);
 
                    // read and set received data
                    ReceivedLinkedMapData receivedLinkedMapData = new ReceivedLinkedMapData();
                    String receiveMessage = readAndSetData(receiveByte, receivedLinkedMapData);
 
                    // set response data
                    String dataAll = buildData();
                    String sendMessage = receiveMessage + dataAll;
 
                    // send bytes
                    byte[] sendBytes = sendMessage.getBytes("UTF-8");
                    int sendLength = sendBytes.length;
                    dos.writeInt(sendLength);
                    dos.write(sendBytes, 0, sendLength);
                    dos.flush();
 
                    System.out.println("\n[ Data Send Success ]");
                    System.out.println("[ Length ] " + sendLength);
                    System.out.println("[ Message ] " + sendMessage);
                }
            } catch (IOException e) {
//                e.printStackTrace();
            } finally {
                try {
                    if (this.socket != null) {
                        System.out.print("\n[ Socket closed ] ");
                        System.out.println("Disconnected :" + this.socket.getInetAddress().getHostAddress() + ":"
                                + this.socket.getPort());
                        this.socket.close();
                    }
                } catch (Exception e) {
                }
            }
        }
    }
 
    public TcpServerExample(int portNo) {
        tcpServerPort = portNo;
        try {
            ServerSocket serverSocket = new ServerSocket();
            serverSocket.bind(new InetSocketAddress(tcpServerPort));
            System.out.println("Starting tcp Server: " + tcpServerPort);
            System.out.println("\n[ Waiting ]\n");
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("Connected " + socket.getLocalPort());
                Server tcpServer = new Server(socket);
                tcpServer.start();
            }
        } catch (IOException io) {
            io.getStackTrace();
        }
    }
 
    private String readAndSetData(byte[] receiveByte, ReceivedLinkedMapData receivedLinkedMapData)
            throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        LinkedHashMap<StringString> linkedHashMap = new LinkedHashMap<StringString>();
        if (ReceivedMapDataGlobal.receivedMapDataGlobal == null || ReceivedMapDataGlobal.receivedMapDataGlobal.size() == 0) {
            ReceivedMapDataGlobal.receivedMapDataGlobal = new HashMap<String, ReceivedLinkedMapData>();
        }
 
        for (int i = 0; i < arrayId.length - 1; i++) {
            System.arraycopy(receiveByte, sumUpArray(arrayId, i), arrayByte[i + 1], 0, arrayId[i + 1]);
            String newStr = new String(arrayByte[i + 1], "UTF-8");
            System.out.println("\n[ " + arrayStr[i + 1+ " ] " + "\'" + newStr + "\'");
            sb.append(newStr);
            linkedHashMap.put(arrayKey[i + 1], newStr.trim());
        }
        String sendMessage = sb.toString();
        receivedLinkedMapData.receivedLinkedHashMap = linkedHashMap;
        
        System.arraycopy(receiveByte, sumUpArray(arrayId, 2), arrayByte[3], 0, arrayId[3]);
        String newStr = new String(arrayByte[3], "UTF-8");
//        System.out.println("\n[ " + arrayStr[3] + " ] " + "\'" + newStr + "\'\n");
        if (ReceivedMapDataGlobal.receivedMapDataGlobal.containsKey(newStr)) {
            ReceivedMapDataGlobal.receivedMapDataGlobal.get(newStr);
        } else {
            ReceivedMapDataGlobal.receivedMapDataGlobal.put(newStr, receivedLinkedMapData);
        }
 
        return sendMessage;
    }
 
    private String buildData() {
        String msgCode = "";
        String msgCode_01 = "TCP0001";
        msgCode = msgCode_01;
        String msgContent = "Response OK";
        msgContent = appendData(msgContent);
        String cnt = "4    ";
        String data1 = "11111111            은행계좌01      bank01              active              ";
        String data2 = "22222222            은행계좌02      bank02              active              ";
        String data3 = "33333333            은행계좌03      bank03              active              ";
        String data4 = "44444444            은행계좌04      bank04              active              ";
        String dataAll = msgCode + msgContent + cnt + data1 + data2 + data3 + data4;
 
        return dataAll;
    }
 
    private static String appendData(String msg) {
        int length = 80;
        int a = length - msg.getBytes().length;
        StringBuilder sb = new StringBuilder();
        sb.append(msg);
        for (int i = 0; i < a; i++) {
            sb.append(" ");
        }
        String result = sb.toString();
        return result;
    }
 
    private int sumUpArray(int[] arrayId, int i) {
        int sum = 0;
        for (int j = 0; j <= i; j++) {
            sum += arrayId[j];
        }
        return sum;
    }
 
}

 

 

Client - readInt, writeInt 활용

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
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
 
public class TcpClientExample {
    
    public static void main(String[] args) throws Exception {
        
        Socket socket = null;
 
        try {
            socket = new Socket();
            System.out.println("\n[ Request ... ]\n");
            socket.connect(new InetSocketAddress("localhost"9999));
            System.out.println("\n[ Success ... ]\n");
 
            byte[] bytes = null;
            String message = null;
            OutputStream os = socket.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
//            message = "0078IF0001      NEXT0112345678901234567890123456789012INQ0001 2021012920210129";
//            message = "0078IF0002      NEXT0112345678901234567890123456789012INQ0001 2021012920210129";
//            message = args[0];
            message = "IF0002      NEXT0112345678901234567890123456789099INQ0001 2021012920210129";
            bytes = message.getBytes("UTF-8");
            
            dos.writeInt(bytes.length);
            dos.write(bytes, 0, bytes.length);
            dos.flush();
            
            System.out.println("\n[ Data Send Success ]\n" + message);
 
            InputStream is = socket.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            
            int leng = dis.readInt();
            System.out.println("leng: " + leng);
 
            if (leng > 0) {
                byte input[] = new byte[leng];
                dis.readFully(input, 0, leng);
                
                message = new String(input, 0, leng, "UTF-8");
                System.out.println("\n[ Data Received ]\n" + message);
            }
 
            os.close();
            is.close();
 
            socket.close();
            System.out.println("\n[ Socket closed ]\n");
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        if (!socket.isClosed()) {
            try {
                socket.close();
                System.out.println("\n[ Socket closed ]\n");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 
    }
 
}

 

< Client >

 

< Server >

 

반응형