'HashMap'에 해당되는 글 2건

전체 채팅


전체 채팅은 채팅서버 관리자나 유료서비스 등으로 전체 채팅사용자를 위한 서비스이다.


해쉬맵을 이용해 사용자를 관리하기 때문에  <String, PrintWriter>

채팅할 때 마다 DB에서 사용자를 조회하지 않아도 된다.


...

Iterator<String> it = clientMap.keySet().iterator();


while (ity.hasNext()) {

mem = ity.next();

PrintWriter it_out = (PrintWriter) clientMap.get(mem);


it_out.println(URLEncoder.encode("##전체##[" + time.format(today) + "] [" + user + "] " + msg, "UTF-8"));

}


...



전체 채팅은 간단하다.

일단 해쉬맵에 있는 사용자를 불러오는 방법은 Iterator로 하면 된다.

Iterator란 자바의 Collection Framework(자료구조)에서 컬렉션에 저장되어 있는 요소들을 읽어오는 방법 중 하나이다.


해쉬맵에서 사용자 이름(Key값)을 불러와 Value값인 Printwriter를 이용해 채팅을 보낸다. it_out.println(내용);



--------------------------


방 채팅


방 채팅은 한마디로 같은 방에 있는 사람에게만 채팅이 보내지는 것이다. 이게 일반적인 채팅이라고 할 수 있다.

그러기 위해선 먼저 채팅을 보내는 사람이 어느 방에 있는지를 파악해야한다. 그리고 같은 방에 누가있는지 파악해야한다.


사용자가 들어올때 Hashmap에 사용자의 닉네임과 Printwriter를 저장했다. clientMap.put(name + "@1", out);

(DB를 사용해 파악을 한다면 쉽겠지만 채팅할 때마다 DB를 조회한다면 DB접속이 많아져 추천하지않는다.)


닉네임 뒤에 @방번호를 넣어 사용자를 관리한다. 그리고 방 이동시에 @뒤에 있는 방번호를 해당 방번호로 바꾸면 된다.



...

if (uname.contains("@")) {

int idq = uname.indexOf("@");

uname = uname.substring(0, idq);

}

Iterator<String> it = clientMap.keySet().iterator();


while (it.hasNext()) {

mem = it.next();

if (mem.contains(user))

user = mem; // mname@rloc

}


int idq = user.indexOf("@");


String rmNum = user.substring(idq + 1); // 방번호 추출


String msg = chkBannWord(chkmsg);



int cnt = 0;

Iterator<String> ity = clientMap.keySet().iterator();

while (ity.hasNext()) {

mem = ity.next();

try {

PrintWriter it_out = (PrintWriter) clientMap.get(mem);

it_out.println(URLEncoder.encode("[" + time.format(today) + "] [" + uname + "] " + msg, "UTF-8"));

}

} catch (Exception e) {

// TODO: handle exception

}

}

}


...

블로그 이미지

허니눈

,
public class 클래스명{

ServerSocket serverSocket = null;
Socket socket = null;

Map<string, printwriter=""> clientMap;

static {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
}

// 생성자
public 클래스명() {
// 클라이언트의 출력스트림을 저장할 해쉬맵 생성
clientMap = new HashMap<string, printwriter="">(); // 사용자 전체 Map
// 해쉬맵 동기화 설정
Collections.synchronizedMap(clientMap);
}

public void init() {
try {
serverSocket = new ServerSocket(portNum);
System.out.println("서버가 시작되었습니다.");

while (true) {

socket = serverSocket.accept();
System.out.println(socket.getInetAddress() + ":" + socket.getPort());

Thread msr = new MultiServerT(socket); // 쓰레드 생성
msr.start();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

/*
======================================


여기에 채팅에 필요한 메소드 만들면 됨


========================================
*/

       public static void main(String[] args) {
// TODO Auto-generated method stub

// 서버 객체 생성
Linux_MultiServer ms = new Linux_MultiServer();
ms.init();

}

// 내부 클래스
// 클라이언트로부터 읽어온 메시지를 다른 클라이언트(socket)에 보내는 역할을 하는 메서드

class MultiServerT extends Thread {
Socket socket;
PrintWriter out = null;
BufferedReader in = null;

// 생성자
public MultiServerT(Socket socket) {
this.socket = socket;
try {
out = new PrintWriter(this.socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(this.socket.getInputStream(), "UTF-8"));
} catch (Exception e) {
System.out.println("예외 T: " + e);
}
}

// 쓰레드를 사용하기 위해서 run()메서드 재정의
@Override
public void run() {

// String s = "";
String name = ""; // 클라이언트들로부터 받은 이름을 저장할 변수

try {

name = in.readLine(); // 클라이언트에서 처음으로 보내는 메시지는
// 클라이언트가 사용할 이름이다.
name = URLDecoder.decode(name, "UTF-8");

clientMap.put(name + "@1", out); // 사용자 전체 해쉬맵에 키를 name으로 출력스트림 객체를 저장

// 입력스트림이 null이 아니면 반복
String s = "";

while (in != null) {
s = in.readLine();
s = URLDecoder.decode(s, "UTF-8");
if ((s.equals("/?")) || (s.equals("/help")) || (s.equals("/h")))
menuList(name, out);
}
} catch (Exception e) {
System.out.println("예외 run: " + e);
} finally {
System.out.println("Bye...");
// 예외가 발생할 때 퇴장. 해쉬맵에서 해당 데이터 제거
// 보통 종료하거나 나가면 java.net.SocketException: 예외 발생

clientMap.remove(u);
sendAllMsg("", name + " 님이 로그아웃하셨습니다.");
System.out.println("현재 접속자 수는 " + clientMap.size() + "명 입니다.");
try {
in.close();
out.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

}




DB와 해쉬맵으로 사용자를 관리하면 된다. 채팅 서버에 처음 접속하면 사용할 name을 입력받는다. 

해쉬맵에 사용자 name과 out(PrintWrite)을 넣어 관리한다.

쓰레드를 이용해 하나의 서버에 여러명의 클라이언트가 접속해 채팅을 할 수 있도록 한다.

'프로젝트 > Java 프로젝트' 카테고리의 다른 글

채팅하기 2. 귓속말(고정귓속말, 일회성귓속말)  (0) 2018.09.25
채팅하기 1. 전체 채팅, 방 채팅  (0) 2018.09.24
Connection Pool  (0) 2018.09.24
클라이언트측 Sender  (0) 2018.09.24
클라이언트측  (0) 2018.09.24
블로그 이미지

허니눈

,