왓? 자바에서 서버 클라이언트 1대1 실시간 통신 예제가 있다고?


안녕하세요

이번 시간에는 이전 예제 에코 서버와 클라이언트의 정적인 채팅이 아닌

실시간 채팅 예제를 올려봅니다.

스레드 하나를 썼을 뿐인데 실시간이 지원되네요

어쨋든 소스 코드 올려봅니다.

렛츠고~!


=========================================================


public class ConsoleChatServer {

ServerSocket server;
Socket sock;
BufferedReader key, in;
PrintWriter pout;
final int port=7777;

public ConsoleChatServer(){
try {
out.println("ConsoleChatServer Started..");
server=new ServerSocket(port);
sock = server.accept();
out.println("##클라이언트와 연결됬음##["+sock.getInetAddress()+"]");
//1) 키보드 입력 스트림 생성
key=new BufferedReader(new InputStreamReader(System.in));
//2) 클라이언트의 메시지를 듣는 스트림
in=new BufferedReader(new InputStreamReader(sock.getInputStream()));
//3) 클라이언트에게 메시지를 보내는 스트림
pout=new PrintWriter(sock.getOutputStream(),true);
//4) 클라이언트의 메시지를 듣는 스레드 동작
ChatThread listener=new ChatThread();
listener.start();
//5) 키보드 입력을 통해 클라이언트에게 메시지를 보낸다
String mymsg="";
while((mymsg=key.readLine())!=null){
pout.println(mymsg);
}
} catch (Exception e) {
out.println("예외: "+e);
closeAll();
}
}// 생성자 ------------------------
//inner class
class ChatThread extends Thread{
// 클라이언트가 보내오는 메시지를 무한정 듣고 콘솔에 출력한다.
public void run(){
try{
while(true){
String cmsg=in.readLine();
out.println("From Client>>"+cmsg);

}//while------
}catch(IOException e){
out.println("예외:[클이 퇴장했어요] "+e);
closeAll();
}
}//run()------
} ///////////////////////
private void closeAll(){
try {
if(in!=null) in.close();
if(pout!=null) pout.close();
if(key!=null) key.close();
if(sock!=null) sock.close();
if(server!=null) server.close();
} catch (Exception e) {
out.println("closeAll()에서 예외 : "+e);
}
}
public static void main(String[] args) throws IOException {
new ConsoleChatServer();
}
}


=========================================================

위의 예제는 서버이고, 아래 예제는 클라이언트입니다.



=========================================================


public class ConsoleChatClient {

String ip="192.168.10.12";
final int port = 7777;
Socket sock;
//키보드입력, 서버로부터 듣는거
BufferedReader key, in;
PrintWriter pw;

//?
public ConsoleChatClient() throws IOException{
//소켓 객체 생성
sock = new Socket(ip, port);
out.println("##서버와 접속됨");

//필요한 스트림 생성 또는 할당
//키보드 입력
key = new BufferedReader(new InputStreamReader(System.in));

InputStream is=sock.getInputStream();
in = new BufferedReader(new InputStreamReader(is));

// PrintWriter 자체가 브리지 스트림을 안거친다. 그래서 BufferedWriter를 안쓴다
pw = new PrintWriter(sock.getOutputStream(),true);

//서버의 메시지를 듣는 스레드 생성 및 동작
ChatThread listener=new ChatThread();
listener.start();

//키보드 입력해서 서버에 메시지 전송
String mymsg="";
while((mymsg=key.readLine())!=null){
pw.println(mymsg);
}
}
class ChatThread extends Thread{
public void run(){
try {
while(true){
String smsg=in.readLine();
out.println("From Server>>"+smsg);
}
} catch (IOException e) {
out.println("예외:[서버가 퇴장했어요] "+e);
closeAll();
}
}
}
private void closeAll(){
try{
//순서? DB는 반드시 순서를 지켜야한다
if(in!=null) in.close();
if(key!=null) key.close();
if(pw!=null) pw.close();
if(sock!=null) sock.close();
}catch(IOException e){
out.println("closeAll()에서 예외 : "+e);
}
}

public static void main(String[] args) throws IOException { // 최종적으로 IOException은 JVM이 처리
new ConsoleChatClient();
}
}

=========================================================


사실 이번 예제는 이전 에코서버 예제와 그렇게 큰 차이는 없으나

스레드의 유무로 훨씬 더 개선된 퍼포먼스를 내는 채팅이 구현되었습니다.

자 그럼 실행화면 보실까요~!



위와 같이 서버를 실행하고 이후 클라이언트를 실행하면

서버에 접속되었다는 멘트가 출력이 됩니다

그리고 서버에게 '안녕하세요 클라이언트입니다' 라고 메시지를 보내게 되면





서버에서 클라이언트가 보낸 메시지가 출력이 되고

서버도 클라이언트에게 메시지를 보내면..





클라이언트도 서버가 보낸 메시지를 출력하게 됩니다

다음 예제에서도 알찬 예제로 찾아뵙겠습니답~!!


댓글 1개: