프로그래밍/Java

intellij java8 웹소켓 서버 (WebSocket Server) 구축

소행성왕자 2021. 11. 10. 15:46

intellij 를 이용하여 웹소켓 서버를 구축해보도록 할께요.

.새 프로젝트 시작

Create New Project

.초기설정

  • Spring MVC
  • Web Application > WebServices

.프로젝트 이름 설정

WebSocket Server 로 설정

우측 하단 Finish 클릭

.웹소켓 사용하기 위한 javax webSocket 설치

.패키지 추가

ChatServer

.java Class 추가

ChatServer

ChatServer.java
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@ServerEndpoint("/ws")
public class ChatServer {
private Map<String, String> usernames = new HashMap<String, String>();
@OnOpen
public void open(Session session) throws IOException, EncodeException {
session.getBasicRemote().sendText("(Server) hello");
}
@OnClose
public void close(Session session) throws IOException, EncodeException {
String userId = session.getId();
if(usernames.containsKey(userId)) {
String username = usernames.get(userId);
for(Session peer : session.getOpenSessions())
peer.getBasicRemote().sendText("(Server): "+username+" left the chat room.");
}
}
@OnMessage
public void handleMessage(String message, Session session) throws IOException, EncodeException {
String userId = session.getId();
if (usernames.containsKey(userId)) {
String username = usernames.get(userId);
for (Session peer : session.getOpenSessions())
peer.getBasicRemote().sendText("(" + username + "): " + message);
} else {
if (usernames.containsValue(message) || message.toLowerCase().equals("server"))
session.getBasicRemote().sendText("(Server): That username is already in use. Please try again.");
else {
usernames.put(userId, message);
session.getBasicRemote().sendText("(Server): Welcome, " + message + "!");
for (Session peer : session.getOpenSessions())
if (!peer.getId().equals(userId))
peer.getBasicRemote().sendText("(Server): " + message + " joined the chat room.");
}
}
}
}
index.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chat</title>
</head>
<body style="margin:0;">
<textarea title="Chat Log" id="log" readonly
style="display: block; width: 100%; height: 600px; resize: none; margin: 0; padding: 0; border: 0;"></textarea>
<input title="Chat Input" id="input" type="text" style="display: block; width: 100%; border-width: 1px 0 1px 0;"
autofocus/>
<script>
var ws = new WebSocket("ws://localhost:8080/ws");
ws.onmessage = function (event) {
console.log(event.data);
document.getElementById("log").value += "[" + timestamp() + "] " + event.data + "\n";
}
document.getElementById("input").addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
ws.send(event.target.value);
event.target.value = "";
}
});
function timestamp() {
var d = new Date(), minutes = d.getMinutes();
if (minutes < 10) minutes = '0' + minutes;
return d.getHours() + ':' + minutes;
}
</script>
</body>
</html>

.톰캣 설정

.톰캣 실행

.이슈

톰캣 시작시 에러
Artifact websocket:war exploded: Error during artifact deployment. See server log for details.

web/WEB-INF/web.xml 내용을 지우고 아래것만 남김
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
</web-app>

.완료

https://youtu.be/aWYr4xj7iYc