1. 서버
package ex20.ch04;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
// Multiflex (채팅)
public class MyServer04 {
private List<ManagerThread> threads = new ArrayList<>();
class ManagerThread extends Thread {
private String username; // s1, s2, s3
private Socket socket;
private BufferedReader br;
private BufferedWriter bw;
public ManagerThread(Socket socket) {
this.socket = socket;
try {
this.br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void setUsername() {
try {
username = br.readLine();
System.out.println(username + " connected");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String getUsername() {
return username;
}
@Override
public void run() {
send("당신의 아이디를 전달해주세요");
setUsername();
send("당신의 아이디는 " + getUsername() + "입니다");
while (true) {
try {
String msg = br.readLine();
// 1. 파싱
String[] sps = msg.split(":"); // ALL:msg, ssar:msg
String protocal = sps[0];
String body = sps[1];
// 2. 프로토콜 분석
if (protocal.equals("ALL")) {
for (ManagerThread mt : threads) {
mt.send(body); // 전체 메시지
}
} else {
for (ManagerThread mt : threads) {
if (protocal.equals(mt.getUsername())) {
mt.send(body); // 귓속말
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public void send(String msg) {
try {
bw.write(msg);
bw.write("\n");
bw.flush();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public MyServer04() {
try {
ServerSocket serverSocket = new ServerSocket(20000);
while (true) {
Socket socket = serverSocket.accept();
ManagerThread mt = new ManagerThread(socket);
threads.add(mt);
mt.start(); // 분신
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
new MyServer04();
}
}
2. 클라이언트
package ex20.ch04;
import java.io.*;
import java.net.Socket;
public class MyClient04 {
public static void main(String[] args) {
try {
Socket socket = new Socket("192.168.0.99", 20000); // 소켓 연결
// 1. 쓰기 분신
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
new Thread(() -> {
while (true) {
try {
String reqBody = keyboard.readLine();
bw.write(reqBody);
bw.write("\n");
bw.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
// 2. 읽기 분신
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
new Thread(() -> {
while (true) {
try {
String reqBody = br.readLine();
System.out.println("서버로 부터 받은 메시지 : " + reqBody);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Share article