다중 채팅 서버
package 다중채팅서버;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
class MultiChatServer {
public static void main(String[] args) {
int port = 8900;
try {
ServerSocket serverSocket = new ServerSocket(port);
while(true) {
Socket socket = serverSocket.accept();
Thread serverTh = new ServerSocketTh(socket);
serverTh.start();
}
} catch(IOException e) {}
}
}
class ServerSocketTh extends Thread {
Socket socket;
static List<Socket> sockets = new ArrayList<>();
public ServerSocketTh(Socket socket) {
this.socket = socket;
sockets.add(socket);
}
@Override
public void run() {
try {
while(true) {
String str;
InputStream input = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(input);
BufferedReader reader = new BufferedReader(isr);
if((str = reader.readLine()) != null) {
System.out.println(str);
for(int i = 0; i < sockets.size(); i++) {
OutputStream out = sockets.get(i).getOutputStream();
PrintWriter writer = new PrintWriter(out, true);
writer.println(str);
}
}
}
} catch (IOException e) {}
}
}
다중 채팅 클라이언트
- BufferedReader / BufferedWriter : 버퍼를 이용해서 읽고 쓴 메소드이며, 버퍼를 이용하기 때문에 입/출력의 효율이 비교할 수없을 정도로 좋아 집니다.
package 다중채팅클라이언트;
import java.net.Socket;
import java.util.Scanner;
public class MultiChatClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8900);
System.out.println("서버 접속 성공");
Scanner sc = new Scanner(System.in);
System.out.print("이름을 설정 하세요 : ");
Thread sndTh = new MultiSnd(socket, sc.nextLine());
Thread rcvTh = new MultiRcv(socket);
sndTh.start();
rcvTh.start();
} catch(Exception e) {
System.out.println("서버 접속 실패!!");
}
}
}
public class MultiRcv extends Thread {
Socket socket;
public MultiRcv(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
InputStream input;
InputStreamReader isr;
BufferedReader reader;
String str = null;
try {
while(true) {
input = socket.getInputStream();
isr = new InputStreamReader(input);
reader = new BufferedReader(isr);
if((str = reader.readLine()) != null) {
System.out.println(str);
}
}
} catch (IOException e) {}
}
}
public class MultiSnd extends Thread {
Socket socket;
String name;
Scanner sc;
public MultiSnd(Socket socket, String name) {
sc = new Scanner(System.in);
this.socket = socket;
this.name = name;
}
@Override
public void run() {
try {
while(true) {
OutputStream out = socket.getOutputStream();
PrintWriter write = new PrintWriter(out, true);
write.println(name + " : " + sc.nextLine());
}
} catch (IOException e) { }
}
}