1:1 통신이 성공하고 난 후 채팅을 만들 때는 클라이언트가 접속을 하면 각각의 클라이언트를 List에 저장을하고 하나의 클라이언트가 메시지를 보내오면 

그 메시지를 List의 모든 클라이언트에게 전송하는 것입니다.


1. Spring Web Socket을 위한 의존성 

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-websocket</artifactId>

<version>${org.springframework-version}</version>

</dependency>


2. 채팅을 위한 웹 소켓 서버 클래스를 생성 

=> com.seunghoo.na.service.ChatHandler클래스 

=> TextWebSocketHandler을 상속받아야합니다.


package com.seunghoo.na.service;


import java.util.ArrayList;

import java.util.List;


import org.springframework.stereotype.Component;

import org.springframework.web.socket.CloseStatus;

import org.springframework.web.socket.TextMessage;

import org.springframework.web.socket.WebSocketSession;

import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component

public class ChatHandler extends TextWebSocketHandler {

// 접속한 클라이언트 세션들을 저장할 LIST를 생성

// 이 List는 1개만 만들어져야 하므로 static으로 선언

private static List<WebSocketSession> list = new ArrayList<WebSocketSession>();


//클라이언트가 접속 했을 때 호출될 메소드 

//클라이언트가 접속 했을 때 호출되는 메소드 

@Override

public void afterConnectionEstablished(WebSocketSession session) throws Exception {

list.add(session);

System.out.println("하나의 클라이언트가 연결됨 ");

}

//클라이언트가 메시지를 보냈을 때 호출되는 메소드 

@Override

protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

// 전송된 메시지를 List의 모든 세션에 전송

String msg = message.getPayload();

for (WebSocketSession s : list) {

s.sendMessage(new TextMessage(msg));

}

}


// 클라이언트의 접속이 해제 되었을 때 호출되는 메소드

@Override

public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {

System.out.println("클라이언트와 연결 해제됨");

list.remove(session);

}

}



3. home.jsp 파일에 채팅창으로 이동하는 링크를 추가 

<a href ="chat"> 채팅 </a>


4. HomeController에서 chat 요청이 왔을 때 chat.jsp로 이동하도록 메소드 생성 

@RequestMapping(value = "chat", method = RequestMethod.GET)

public void chat(Locale locale, Model model) {

}


5. ChatHandler클래스를 웹 소켓으로 등록 : Servlet-context.xml 파일 

<websocket:mapping handler="chatHandler" path="/chat-ws"/>

6. views 디렉토리에 채팅페이지(chat.jsp)를 생성

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

<div id="one">

별명:<input type="text" id="nickname" /> <input type="button"

id="enter" value="입장" />

</div>

<div id="two" style="display: none">

<input type="button" id="exit" value="퇴장" /><br />

<div id="chatarea" style="width:400px; height:600px; border:1px solid;"></div>

<input type="text" id="message" /> <input type="button" id="send"

value="보내기" />

</div>


</body>

<script>

one = document.getElementById("one");

two = document.getElementById("two");


document.getElementById("enter").addEventListener("click", function() {

//웹 소켓 연결해주는 함수 호출 

connect();

});


document.getElementById("exit").addEventListener("click", function() {

//연결을 해제해주는 함수 호출 

disconnect();

});

document.getElementById("send").addEventListener("click", function() {

//연결을 해제해주는 함수 호출 

send();

});

var websocket;

//입장 버튼을 눌렀을 때 호출되는 함수 

function connect(){

websocket = new WebSocket("ws://localhost:9000/na/chat-ws");

//웹 소켓에 이벤트가 발생했을 때 호출될 함수 등록 

websocket.onopen = onOpen;

websocket.onmessage = onMessage;

websocket.onclose = onClose;

}

//퇴장 버튼을 눌렀을 때 호출되는 함수 

function disconnect(){

msg = document.getElementById("nickname").value;

websocket.send(msg+"님이 퇴장하셨습니다");

websocket.close();

}

//보내기 버튼을 눌렀을 때 호출될 함수 

function send(){

nickname = document.getElementById("nickname").value;

msg = document.getElementById("message").value;

websocket.send(nickname + ":"+ msg);

document.getElementById("message").value = "";

}

//웹 소켓에 연결되었을 때 호출될 함수 

function onOpen(){

nickname = document.getElementById("nickname").value;

websocket.send(nickname + "님 입장하셨습니다.");

}

//웹 소켓에서 연결이 해제 되었을 때 호출될 함수 

function onMessage(evt){

data= evt.data;

chatarea = document.getElementById("chatarea");

chatarea.innerHTML = data + "<br/>" + chatarea.innerHTML

function onClose(){

}

</script>

</html>



+ Recent posts