forked from AidaLf/SBU_AP_Project_Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClientThread.java
56 lines (46 loc) · 1.97 KB
/
ClientThread.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
import java.io.*;
import java.net.*;
import java.nio.*;
import java.util.*;
import com.google.gson.*;
public class ClientThread extends Thread{
Socket socket;
DataOutputStream out = null;
DataOutputStream in = null;
// Gson gson = new GsonBuilder().setPrettyPrinting().setLenient().create();
Gson gson = new GsonBuilder().setLenient().create();
public ClientThread(Socket socket) {
this.socket = socket;
}
@Override
public void run () {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null ) {
sb.append(line).append(System.lineSeparator());
break;
}
String content = sb.toString();
//System.out.println(content);
String modified = content.substring(2, content.length());
//System.out.println(modified.charAt(modified.length() - 2));
JsonElement jsonElement = JsonParser.parseString(modified);
JsonObject jsonObject = jsonElement.getAsJsonObject();
System.out.println("Client request: "+jsonObject.toString());
//getting the request and handling it
APIRequest req = gson.fromJson(jsonObject, APIRequest.class);
APIResponse response = BackendServer.handleRequest(req);
String str = gson.toJson(response,APIResponse.class);
System.out.println("Server response: "+str+"\n");
dout.writeUTF(str);
dout.flush();
dout.close();
socket.close();
} catch (IOException e) {
System.out.println("Error occurred: " + e.getMessage());
} //catch (InterruptedException i) {System.out.println("interrupt exception");}
}
}