채팅
SocketHandler
package com.oracle.oBootMybatis01.handler;
import java.util.HashMap;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
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;
@SuppressWarnings("unchecked")
@Component
public class SocketHandler extends TextWebSocketHandler {
HashMap<String, WebSocketSession> sessionMap = new HashMap<>();
HashMap<String, String> sessionUserMap = new HashMap<>();
JSONObject jsonUser = null;
@SuppressWarnings("unchecked")
public void handleTextMessage(WebSocketSession session , TextMessage message) {
String msg = message.getPayload();
System.out.println("SocketHandler handleTextMessage msg->"+msg);
JSONObject jsonObj = jsonToObjectParser(msg);
String msgType = (String) jsonObj.get("type");
System.out.println("SocketHandler handleTextMessage msgType->"+msgType);
switch (msgType) {
case "message":
jsonUser = new JSONObject(sessionUserMap);
System.out.printf( "JSONUser: %s", jsonUser);
String yourName = (String) jsonObj.get("yourName");
System.out.println("SocketHandler handleTextMessage yourName->"+yourName);
if (yourName.equals("ALL")) {
for(String key : sessionMap.keySet()) {
WebSocketSession wss = sessionMap.get(key);
try {
System.out.println("message key->"+key);
System.out.println("message wss->"+wss);
wss.sendMessage(new TextMessage(jsonObj.toJSONString()));
}catch(Exception e) {
e.printStackTrace();
}
}
} else {
System.out.println("개인 전송 대상자 상대방 sessionID-->"+yourName);
WebSocketSession wss1 = sessionMap.get(yourName);
try {
wss1.sendMessage(new TextMessage(jsonObj.toJSONString()));
}catch(Exception e) {
e.printStackTrace();
}
String meName = (String) jsonObj.get("sessionId");
WebSocketSession wss2 = sessionMap.get(meName);
System.out.println("개인 전송 대상자 나-->"+meName);
try {
wss2.sendMessage(new TextMessage(jsonObj.toJSONString()));
}catch(Exception e) {
e.printStackTrace();
}
}
break;
case "userSave":
String sessionId = (String) jsonObj.get("sessionId");
String userName = (String) jsonObj.get("userName");
String saveStatus = (String) jsonObj.get("saveStatus");
if (saveStatus.equals("Create") ) {
sessionUserMap.put(sessionId, userName);
System.out.println("==================================================");
System.out.println("== sessionUserMap 저장내용 조회하여 arrayJsonUser에 ==");
System.out.println("== 각각의 JSONObject jsonUser로 변환 ==");
System.out.println("== 1. type : userSave ==");
System.out.println("== 2. sessionId : sessionUserMap.sessionId ==");
System.out.println("== 3. userName : sessionUserMap.userName ==");
System.out.println("=================================================");
} else {
System.out.println("handleTextMessage userDelete start.. ");
System.out.println("handleTextMessage userDelete session.getId()->"+session.getId());
sessionMap.remove(session.getId());
sessionUserMap.remove(session.getId());
}
JSONArray arrayJsonUser = new JSONArray();
System.out.println("== 1. type : userSave ==");
Iterator<String> mapIter = sessionUserMap.keySet().iterator();
System.out.println("== 2. sessionId : sessionUserMap.sessionId ==");
System.out.println("== 3. userName : sessionUserMap.userName ==");
while(mapIter.hasNext()){
String key = mapIter.next();
String value = sessionUserMap.get( key );
System.out.println("Key : Value -->"+key+" : "+value);
jsonUser = new JSONObject();
jsonUser.put("type", "userSave");
jsonUser.put("sessionId",key);
jsonUser.put("userName",value);
arrayJsonUser.add(jsonUser);
}
System.out.println("====== session을 Get하여 User 내용 전송 ========");
System.out.printf( "arrayJsonUser: %s", arrayJsonUser);
for(String key : sessionMap.keySet()) {
WebSocketSession wss = sessionMap.get(key);
try {
wss.sendMessage(new TextMessage(arrayJsonUser.toJSONString()));
}catch(Exception e) {
e.printStackTrace();
}
}
break;
case "userDelete":
System.out.println("handleTextMessage userDelete start.. ");
System.out.println("handleTextMessage userDelete session.getId()->"+session.getId());
sessionMap.remove(session.getId());
sessionUserMap.remove(session.getId());
break;
}
}
@SuppressWarnings("unchecked")
public void afterConnectionEstablished(WebSocketSession session) throws Exception
{
System.out.println("SocketHandler afterConnectionEstablished start...");
super.afterConnectionEstablished(session);
sessionMap.put(session.getId(), session);
JSONObject jsonObj = new JSONObject();
jsonObj.put("type", "getId");
jsonObj.put("sessionId", session.getId());
session.sendMessage(new TextMessage(jsonObj.toJSONString()));
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
System.out.println("SocketHandler afterConnectionClosed start...");
sessionMap.remove(session.getId());
super.afterConnectionClosed(session, status);
}
private static JSONObject jsonToObjectParser(String jsonStr) {
JSONParser parser = new JSONParser();
JSONObject jsonObj = null;
try {
jsonObj = (JSONObject) parser.parse(jsonStr);
} catch (ParseException e) {
e.printStackTrace();
}
return jsonObj;
}
}
WebSocketConfig
package com.oracle.oBootMybatis01.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import com.oracle.oBootMybatis01.handler.SocketHandler;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Autowired
SocketHandler socketHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(socketHandler, "/chating");
}
}
SocketController
package com.oracle.oBootMybatis01.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import lombok.extern.slf4j.Slf4j;
@Controller
@Slf4j
public class SocketController {
@RequestMapping("/chat")
public ModelAndView chat() {
System.out.println("SocketController chat start . . . ");
ModelAndView mv = new ModelAndView();
mv.setViewName("chatView");
return mv;
}
}
chatView
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<style>
*{
margin:0;
padding:0;
}
.container{
width: 500px;
margin: 0 auto;
padding: 25px
}
.container h1{
text-align: left;
padding: 5px 5px 5px 15px;
color: #FFBB00;
border-left: 3px solid #FFBB00;
margin-bottom: 20px;
}
.chating{
background-color: #000;
width: 500px;
height: 500px;
overflow: auto;
}
.chating .me{
color: #F6F6F6;
text-align: right;
}
.chating .others{
color: #FFE400;
text-align: left;
}
input{
width: 330px;
height: 25px;
}
#yourMsg{
display: none;
}
#yourNameDel{
display: none;
}
</style>
</head>
<script type="text/javascript">
var ws;
function wsOpen(){
console.log("wsOpen location.host: " + location.host);
var wsUri = "ws://" + location.host + "${pageContext.request.contextPath}/chating";
ws = new WebSocket(wsUri);
wsEvt();
}
function wsEvt() {
console.log("wsEvt start... ");
alert("wsEvt start...")
ws.onopen = function(data){
console.log("wsEvt 소켓이 열리면 초기화 세팅하기..");
}
ws.onmessage = function(data) {
var msg = data.data;
var memberSave = false;
alert("ws.onmessage->"+msg)
if(msg != null && msg.trim() != ''){
memberSave = false;
var jsonMsg = JSON.parse(msg);
if (Array.isArray(jsonMsg)) {
if (Object.keys(jsonMsg).length > 1) {
memberSave = true;
alert("JSONArray jsonMsg Count->"+ Object.keys(jsonMsg).length);
}
}
}
if(jsonMsg.type == "getId"){
alert("jsonMsg.type->getId");
var sid = jsonMsg.sessionId != null ? jsonMsg.sessionId : "";
if(sid != ''){
$("#sessionId").val(sid);
sendUser('Create');
}
}else if(jsonMsg.type == "message"){
alert("jsonMsg.type->message");
if(jsonMsg.sessionId == $("#sessionId").val()){
$("#chating").append("<p class='me'>나 :" + jsonMsg.msg + "</p>");
}else{
$("#chating").append("<p class='others'>" + jsonMsg.userName + " :" + jsonMsg.msg + "</p>");
}
}else if(memberSave == true){
alert("userSave");
$('#member_sub').remove();
var str = " ";
str += " <select name='member' id='member_sub' class='member_sub'> ";
str += " <option value='ALL'>전체 </option> ";
$(jsonMsg).each(
function(){
var str2 = "";
if(jsonMsg.sessionId == $("#sessionId").val()){
alert("내꺼임"+ $("#sessionId").val())
} else {
str2 += " <option value='"+this.sessionId + "'> "+this.userName + "</option> ";
str += str2 ;
}
}
);
str += " </select>"
str += " </div><p>"
$('#member').append(str);
memberSave = false;
}else{
console.warn("unknown type!");
}
}
document.addEventListener("keypress", function(e){
if(e.keyCode == 13){
send();
}
});
}
function sendUser(saveStatus) {
var userOption ={
type : "userSave",
sessionId : $("#sessionId").val(),
userName : $("#userName").val(),
saveStatus : saveStatus
}
alert("sendUser Start..")
ws.send(JSON.stringify(userOption));
}
function chatName(){
alert("chatName Start..");
var userName = $("#userName").val();
console.log("chatName userName: " + userName);
if(userName == null || userName.trim() == ""){
alert("사용자 이름을 입력해주세요.");
$("#userName").focus();
}else{
wsOpen();
$("#meName").append('나의이름:'+userName);
$("#yourName").hide();
$("#yourMsg").show();
}
}
function send() {
var option ={
type: "message",
sessionId : $("#sessionId").val(),
userName : $("#userName").val(),
yourName : $("#member_sub").val(),
msg : $("#chatting").val()
}
ws.send(JSON.stringify(option));
$('#chatting').val("");
}
</script>
<body>
<div id="container" class="container">
<h1>채팅</h1>
<input type="hidden" id="sessionId" value="">
<div id="meName"></div>
<div id="chating" class="chating">
</div>
<div id="member" class="member">
</div>
<div id="yourName">
<table class="inputTable">
<tr>
<th>사용자명</th>
<th><input type="text" name="userName" id="userName"></th>
<th><button onclick="chatName()" id="startBtn">이름 등록</button></th>
</tr>
</table>
</div>
<div id="yourNameDel"></div>
<div id="yourMsg">
<table class="inputTable">
<tr>
<th>메시지</th>
<th><input id="chatting" placeholder="보내실 메시지를 입력하세요."></th>
<th><button onclick="send()" id="sendBtn">보내기</button></th>
</tr>
</table>
</div>
</div>
</body>
</html>