프로그래밍/Java

intellij java11 + spring boot + 웹소켓 서버 (WebSocket Server) 구축

소행성왕자 2023. 5. 3. 14:47

 

프로젝트 폴더(untitled1) 우측 마우스 클릭

Add Framework Supprot...  클릭

WebServices  체크

    Apache Axis 변경

Spring MVC 체크

src/main/java 에서 패키지 생성 (kdh)

.java Class 추가

ChatServer

package kdh;



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.");
            }
        }
    }
}

javax.websocket.*  에서 에러 발생

  • 프로젝트 우클릭 Add Frameword Support > WebSocket 체크 하고 받으면 안됨
  • build.gradle 에 javax 추가
plugins {
    id 'java'
    id 'war'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
    implementation 'javax.websocket:javax.websocket-api:1.1'
}

test {
    useJUnitPlatform()
}

 

src/main/webapp/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>

 

.톰캣 설정

+ 클릭후  tomcat > local 클릭

우측 아래 Fix 클릭

톰캣 시작후 localhost:8080 접속

정상적인 소켓 접속

 

리눅스 서버에서 톰캣7 또는 톰캣8 설치후 server.xml 설정

server.xml

 <Host name="localhost"  appBase="/home/relay/html"  unpackWARs="true" autoDeploy="true">
        <Context path="/" docBase="./untitled-1.0-SNAPSHOT.war" reloadable="false" allowLinking="false" />

/usr/local/tomcat7/bin/shutdown.sh

/usr/local/tomcat7/bin/start.sh