클라이언트가 서버에 연결하기 위해서는 IP 주소와 Port 번호가 있어야 한다.
2: TCP -> UDP
4: UDP -> TCP
new Socket("localhost", 5001);
serverSocket.accept()
좌상단 -> 우상단 -> 좌하단 -> 우하단
InputStream
OutputStream
OutputStream
InputStream
클라이언트로 DatagramPacket을 발신할 때 send() 메소드를 사용한다.
import java.util.Objects;
public class Product {
public Product() {
}
public Product(int no, String name, int price, int stock) {
this.no = no;
this.name = name;
this.price = price;
this.stock = stock;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Product product = (Product) o;
return no == product.no && price == product.price && stock == product.stock && name.equals(product.name);
}
@Override
public int hashCode() {
return Objects.hash(no, name, price, stock);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
@Override
public String toString() {
return "Product{" + "no=" + no + ", name='" + name + '\'' + ", price=" + price + ", stock=" + stock + '}';
}
private int no;
private String name;
private int price;
private int stock;
}
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ProductServer {
private int pk;
private TreeMap<Integer, Product> products;
private ExecutorService es;
public static void main(String[] args) {
ProductServer productServer = new ProductServer();
try {
productServer.start();
} catch (IOException ignored) {
}
}
public void start() throws IOException {
try (ServerSocket ss = new ServerSocket(50001)) {
es = Executors.newFixedThreadPool(100);
products = new TreeMap<>();
System.out.println("[서버] 시작됨");
while (true) {
try {
new SocketClient(ss.accept());
} catch (IOException e) {
break;
}
}
}
}
public class SocketClient {
private Socket sc;
private DataInputStream dis;
private DataOutputStream dos;
public SocketClient(Socket sc) {
try {
this.sc = sc;
this.dis = new DataInputStream(sc.getInputStream());
this.dos = new DataOutputStream(sc.getOutputStream());
receive();
} catch (IOException e) {
try {
sc.close();
} catch (IOException ignored) {
}
}
}
public void receive() {
es.execute(() -> {
while (true) {
try {
JSONObject requestJson = new JSONObject(dis.readUTF());
int menu = requestJson.getInt("menu");
switch (menu) {
case 0 -> getProductList();
case 1 -> createProduct(requestJson);
case 2 -> updateProduct(requestJson);
case 3 -> deleteProduct(requestJson);
}
} catch (IOException e) {
break;
}
}
try {
sc.close();
} catch (IOException ignored) {
}
});
}
public void getProductList() throws IOException {
JSONArray productList = new JSONArray();
JSONObject product;
JSONObject jsonResponse = new JSONObject();
for (Product p : products.values()) {
product = new JSONObject();
product.put("no", p.getNo());
product.put("name", p.getName());
product.put("price", p.getPrice());
product.put("stock", p.getStock());
productList.put(product);
}
jsonResponse.put("status", "success");
jsonResponse.put("data", productList);
dos.writeUTF(jsonResponse.toString());
dos.flush();
}
public void createProduct(JSONObject request) throws IOException {
JSONObject jsonRequest = request.getJSONObject("data");
JSONObject jsonResponse = new JSONObject();
Product product = new Product();
product.setNo(++pk);
product.setName(jsonRequest.getString("name"));
product.setPrice(jsonRequest.getInt("price"));
product.setStock(jsonRequest.getInt("stock"));
products.put(pk, product);
jsonResponse.put("status", "success");
jsonResponse.put("data", new JSONObject());
dos.writeUTF(jsonResponse.toString());
dos.flush();
}
public void updateProduct(JSONObject request) throws IOException {
JSONObject jsonRequest = request.getJSONObject("data");
JSONObject jsonResponse = new JSONObject();
Product product = products.get(jsonRequest.getInt("no"));
product.setName(jsonRequest.getString("name"));
product.setPrice(jsonRequest.getInt("price"));
product.setStock(jsonRequest.getInt("stock"));
jsonResponse.put("status", "success");
jsonResponse.put("jsonRequest", new JSONObject());
dos.writeUTF(jsonResponse.toString());
dos.flush();
}
public void deleteProduct(JSONObject request) throws IOException {
JSONObject jsonRequest = request.getJSONObject("data");
JSONObject jsonResponse = new JSONObject();
products.remove(jsonRequest.getInt("no"));
jsonResponse.put("status", "success");
jsonResponse.put("data", new JSONObject());
dos.writeUTF(jsonResponse.toString());
dos.flush();
}
}
}
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class ProductClient {
private Socket sc;
private DataInputStream dis;
private DataOutputStream dos;
private Scanner scanner;
public static void main(String[] args) {
ProductClient productClient = new ProductClient();
try {
productClient.start();
} catch (IOException ignored) {
}
}
public void start() throws IOException {
scanner = new Scanner(System.in);
sc = new Socket("localhost", 50001);
dis = new DataInputStream(sc.getInputStream());
dos = new DataOutputStream(sc.getOutputStream());
System.out.println("[클라이언트] 서버에 연결됨");
getProductList();
}
public void exit() {
try {
sc.close();
scanner.close();
} catch (Exception ignored) {
}
System.out.println("[클라이언트] 종료됨");
}
public void getResponse() throws IOException {
JSONObject jsonResponse = new JSONObject(dis.readUTF());
if (jsonResponse.getString("status").equals("success")) {
getProductList();
}
}
public void getMenuNumber() throws IOException {
System.out.println();
System.out.println("----------------------------------------------------------");
System.out.println("메뉴: 1.Create | 2.Update | 3.Delete | 4.Exit");
System.out.print("선택: ");
int menuNumber = Integer.parseInt(scanner.nextLine());
System.out.println();
switch (menuNumber) {
case 1 -> createProduct();
case 2 -> updateProduct();
case 3 -> deleteProduct();
default -> exit();
}
}
public void getProductList() throws IOException {
final int MENU_NUM = 1;
JSONObject jsonRequest = new JSONObject();
System.out.println();
System.out.println("[상품 목록]");
System.out.println("----------------------------------------------------------");
System.out.println("no\t\tname\t\t\t\t\tprice\t\t\tstock");
System.out.println("----------------------------------------------------------");
jsonRequest.put("menu", MENU_NUM);
jsonRequest.put("data", new JSONObject());
dos.writeUTF(jsonRequest.toString());
dos.flush();
JSONObject jsonResponse = new JSONObject(dis.readUTF());
if (jsonResponse.getString("status").equals("success")) {
JSONArray jsonArray = jsonResponse.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject product = jsonArray.getJSONObject(i);
System.out.printf("%d\t\t%s\t\t\t\t\t\t%d\t\t\t\t%d\n",
product.getInt("no"),
product.getString("name"),
product.getInt("price"),
product.getInt("stock")
);
}
}
getMenuNumber();
}
public void createProduct() throws IOException {
final int MENU_NUM = 1;
Product product = new Product();
JSONObject jsonProduct = new JSONObject();
JSONObject jsonRequest = new JSONObject();
System.out.println("[상품 생성]");
System.out.print("상품 이름: ");
product.setName(scanner.nextLine());
System.out.print("상품 가격: ");
product.setPrice(Integer.parseInt(scanner.nextLine()));
System.out.print("상품 재고: ");
product.setStock(Integer.parseInt(scanner.nextLine()));
jsonProduct.put("name", product.getName());
jsonProduct.put("price", product.getPrice());
jsonProduct.put("stock", product.getStock());
jsonRequest.put("menu", MENU_NUM);
jsonRequest.put("data", jsonProduct);
dos.writeUTF(jsonRequest.toString());
dos.flush();
getResponse();
}
public void updateProduct() throws IOException {
final int MENU_NUM = 2;
Product product = new Product();
JSONObject jsonProduct = new JSONObject();
JSONObject jsonRequest = new JSONObject();
System.out.println("[상품 수정]");
System.out.print("상품 번호: ");
product.setNo(Integer.parseInt(scanner.nextLine()));
System.out.print("이름 변경: ");
product.setName(scanner.nextLine());
System.out.print("가격 변경: ");
product.setPrice(Integer.parseInt(scanner.nextLine()));
System.out.print("재고 변경: ");
product.setStock(Integer.parseInt(scanner.nextLine()));
jsonProduct.put("no", product.getNo());
jsonProduct.put("name", product.getName());
jsonProduct.put("price", product.getPrice());
jsonProduct.put("stock", product.getStock());
jsonRequest.put("menu", MENU_NUM);
jsonRequest.put("data", jsonProduct);
dos.writeUTF(jsonRequest.toString());
dos.flush();
getResponse();
}
public void deleteProduct() throws IOException {
final int MENU_NUM = 3;
JSONObject jsonProduct = new JSONObject();
JSONObject jsonRequest = new JSONObject();
System.out.println("[상품 삭제]");
System.out.print("상품 번호: ");
int no = Integer.parseInt(scanner.nextLine());
jsonProduct.put("no", no);
jsonRequest.put("menu", MENU_NUM);
jsonRequest.put("data", jsonProduct);
dos.writeUTF(jsonRequest.toString());
dos.flush();
getResponse();
}
}