본문 바로가기
TechNical/JAVA

자바 다중채팅 프로그램(Thread, Socket, SynchonizedList)

by 강멍멍이 2011. 4. 24.
반응형

커맨드 창에서 써 먹어 볼 수 있는 다중 채팅 자바 소스이다.. 책에꺼 냅다 적어 놓은거임.
<뇌를 자극하는 JAVA 프로그래밍>  <- 개인적으로 참 좋은 책이라고 봄. 무작정 외우는게 아니라 이해하게 해줌. ㅎㅎ

쓰레드를 이용해서 메세지를 주고 받고를 동시에 수행하고
여러명이서 동시에 같은 메세지를 볼 수 있게 SynchonizedList를 이용하더라.

... 보고는 알겠는데 안 보고 짜라면 못 할거 같아..ㅠ.ㅠ;;

[Server.java]
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
 /**
  * @param args
  */
 public static void main(String[] args) {
  ServerSocket serverSocket = null;
  try{
   serverSocket = new ServerSocket(9000);
   while(true){
    Socket socket = serverSocket.accept();
    Thread thread = new PerClientThread(socket);
    thread.start();
   }
  } catch (Exception e){
   System.out.println(e.getMessage());
  }
 }
}


[Client.java]
import java.net.Socket;

public class Client {
 public static void main(String[] args){
  if (args.length != 1){
   System.out.println("input name!");
   return;
  }
  
  try{
   Socket socket = new Socket("127.0.0.1", 9000);
   Thread thread1 = new SenderThread(socket, args[0]);
   Thread thread2 = new ReceiverThread(socket);
   thread1.start();
   thread2.start();
  } catch (Exception e){
   System.out.println(e.getMessage());
  }
 }
}


[PerClientThread.java]
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class PerClientThread extends Thread{
 static List<PrintWriter> list = Collections.synchronizedList(new ArrayList<PrintWriter>());
 
 Socket socket;
 
 PrintWriter writer;
 public PerClientThread(Socket socket) {
  this.socket =  socket;
  
  try{
   writer = new PrintWriter(socket.getOutputStream());
   list.add(writer);
  } catch (Exception e) {
   System.out.println(e.getMessage());
  }
 }
 
 public void run(){
  String name = null;
  try{
   BufferedReader reader =  new BufferedReader(new InputStreamReader(socket.getInputStream()));
   name =  reader.readLine();
   sendAll("#" + name + " is Joined");
   while(true){
    String str = reader.readLine();
    if(str == null){
     break;
    }
    sendAll(name + ">" + str);
   }
  } catch (Exception e){
   System.out.println(e.getMessage());
  } finally {
   list.remove(writer);
   sendAll("#" + name + " is out");
   try{
    socket.close();
   } catch (Exception ignored) {    
   }
  }
 }
 
 private void sendAll(String str) {
  for (PrintWriter writer : list){
   writer.println(str);
   writer.flush();
  }
 }
 
}


[ReceiverThread.java]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class ReceiverThread extends Thread{
 Socket socket;
 ReceiverThread(Socket socket){
  this.socket = socket;
 }
 
 public void run() {
  try{
   BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
   while(true){
    String str = reader.readLine();
    if (str == null){
     break;
    }
    System.out.println(str);
   }
  } catch (IOException e){
   System.out.println(e.getMessage());
  }
 }
}

[SenderThread.java]
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class SenderThread  extends Thread{
 Socket socket;
 String name;
 SenderThread (Socket socket, String name){
  this.socket = socket;
  this.name = name;
 }
 public void run(){
  try {
   BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
   PrintWriter writer = new PrintWriter(socket.getOutputStream());
   writer.println(name);
   writer.flush();
   
   while(true){
    String str = reader.readLine();
    if (str.equals("bye")) break;
    writer.println(str);
    writer.flush();
   }
  } catch (Exception e){
   System.out.println(e.getMessage());
  } finally {
   try {
    socket.close();
   } catch (Exception ignored) {}   
  }
 }
}

반응형

댓글