Skip to content

Commit

Permalink
update join room, create room and leave room (#174)
Browse files Browse the repository at this point in the history
* update join room, create room and leave room

* add new model for socketio

* update

* add allow header

* delete empty space

---------

Co-authored-by: [email protected] <under987..A>
Co-authored-by: [email protected] <>
  • Loading branch information
wiroger9595 authored Oct 17, 2023
1 parent 863ab3e commit e808531
Show file tree
Hide file tree
Showing 7 changed files with 120 additions and 20 deletions.
21 changes: 21 additions & 0 deletions domain/src/main/kotlin/tw/waterballsa/gaas/events/SocketioEvent.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package tw.waterballsa.gaas.events

data class SocketioEvent(
var type: String = "",
var data: ChatData = ChatData(),
) {
constructor(type: String, userId: String, nickname: String, target: String) : this(
type,
ChatData(ChatUser(userId, nickname), target),
)
}

data class ChatData(
var user: ChatUser = ChatUser(),
var target: String = "",
)

data class ChatUser(
var id: String = "",
var nickname: String = "",
)
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class ServerCommandLineRunner(private val server: SocketIOServer) : CommandLineR

@PreDestroy
fun stopServer() {
logger.info("Stopping the server...")
server.stop()
server.stop()
logger.info("Server stopped.")

Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
package tw.waterballsa.gaas.spring.configs.socketio

import com.corundumstudio.socketio.AuthorizationListener
import com.corundumstudio.socketio.SocketIOServer
import com.corundumstudio.socketio.listener.DefaultExceptionListener
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.reactive.CorsWebFilter
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource


@Configuration
@EnableConfigurationProperties(SocketIOProperties::class)
class SocketIOConfig (){
class SocketIOConfig{

@Bean
fun socketIOServer(socketIOProperties: SocketIOProperties): SocketIOServer {
Expand All @@ -17,8 +22,12 @@ class SocketIOConfig (){
with(socketIOProperties){
hostname = socketHost
port = socketPort
allowHeaders = "Authorization, CustomHeaderName"
}
}


return SocketIOServer(configuration)
}

}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,100 @@ package tw.waterballsa.gaas.spring.configs.socketio

import com.corundumstudio.socketio.SocketIOClient
import com.corundumstudio.socketio.SocketIOServer
import com.corundumstudio.socketio.listener.DisconnectListener
import com.nimbusds.jose.shaded.json.JSONObject
import io.netty.handler.codec.http.HttpHeaderNames
import org.apache.catalina.manager.util.SessionUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.security.oauth2.jwt.Jwt
import org.springframework.stereotype.Component
import org.springframework.web.context.request.RequestContextHolder
import tw.waterballsa.gaas.application.repositories.RoomRepository
import tw.waterballsa.gaas.application.repositories.UserRepository
import tw.waterballsa.gaas.application.usecases.GetRoomUsecase
import tw.waterballsa.gaas.domain.Room
import tw.waterballsa.gaas.events.SocketioEvent
import javax.servlet.http.HttpServletRequest


@Component
class SocketIOEventHandler(private val socketIOServer: SocketIOServer) {
class SocketIOEventHandler(
private val socketIOServer: SocketIOServer,
protected val roomRepository: RoomRepository,
protected val userRepository: UserRepository,
) {

private val logger: Logger = LoggerFactory.getLogger(SocketIOEventHandler::class.java)


init {
configureEventHandlers()
}

private fun configureEventHandlers() {
socketIOServer.addEventListener(SocketIOEvent.CHAT_MESSAGE.eventName, JSONObject::class.java) { client: SocketIOClient, data: JSONObject, _ ->

fun configureEventHandlers() {

socketIOServer.addConnectListener { client ->
val token = client.handshakeData.httpHeaders.get(HttpHeaderNames.COOKIE)
val customHeader = client.handshakeData.getSingleUrlParam("Authorization")

if (client != null ) {
logger.info("有新用戶連結 , SessionId: {}", client.getSessionId())
val board = socketIOServer.broadcastOperations
logger.info("board clientId {}", board.clients)
}

}

socketIOServer.addEventListener(SocketIOEventName.CHAT_MESSAGE.eventName, SocketioEvent::class.java)
{ client: SocketIOClient, socketioEvent: SocketioEvent, _ ->
// Handle the "chatMessage" event
logger.info(" Received message: $data from client: ${client.sessionId}")
logger.info(" CHAT_MESSAGE Received message: $socketioEvent from client: ${client.sessionId}")
client.handshakeData.getSingleUrlParam("")
// ECHO
client.sendEvent(SocketIOEventName.CHAT_MESSAGE.eventName, socketioEvent.data)
}

socketIOServer.addEventListener(SocketIOEventName.JOIN_ROOM.eventName, SocketioEvent::class.java) {
client: SocketIOClient, socketioEvent: SocketioEvent, _ ->

// ECHO
client.sendEvent(SocketIOEvent.CHAT_MESSAGE.eventName, data)
logger.info(" JOIN_ROOM Received message: $socketioEvent from client: ${client.sessionId}")
val roomSize = client.getCurrentRoomSize(socketioEvent.data.target)

if(roomSize == 0){
logger.info("user: " + client.sessionId + "you are the host ")
} else{
client.joinRoom(socketioEvent.data.target)
logger.info("Client joined room: ${socketioEvent.data.target}")
logger.info("id = " + socketioEvent.data.user.id + " nickname " + socketioEvent.data.user.nickname + " targetRoom " + socketioEvent.data.target)
logger.info(" room size is : ${client.getCurrentRoomSize(socketioEvent.data.target)}")
socketIOServer.getRoomOperations(socketioEvent.data.target).sendEvent(SocketIOEventName.JOIN_ROOM.eventName, socketioEvent.data.user.id)
}
}

socketIOServer.addEventListener(SocketIOEvent.CHATROOM_JOIN.eventName, JSONObject::class.java) {
client: SocketIOClient, data: JSONObject, _ ->

socketIOServer.addEventListener(SocketIOEventName.LEAVE_ROOM.eventName, SocketioEvent::class.java) {
client: SocketIOClient, socketioEvent: SocketioEvent, _ ->
// ECHO
logger.info(" Received message: $data from client: ${client.sessionId}")
logger.info(" LEAVE_ROOM Received message: ${socketioEvent.data.target} from client: ${client.sessionId}")

client.leaveRoom(socketioEvent.data.target)
socketIOServer.removeNamespace(socketioEvent.data.target)
}


socketIOServer.addEventListener(SocketIOEventName.DISCONNECT.eventName, SocketioEvent::class.java) {
client: SocketIOClient, socketioEvent: SocketioEvent, _ ->

client.disconnect()
logger.info(" client is leaven room with key disconnect")
}

client.sendEvent(SocketIOEvent.CHATROOM_JOIN.eventName, data)
socketIOServer.addDisconnectListener {
client: SocketIOClient ->
logger.info("Server disconnected on the server side")
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package tw.waterballsa.gaas.spring.configs.socketio

enum class SocketIOEventName (val eventName: String){
CHAT_MESSAGE("CHAT_MESSAGE"),
CHATROOM_JOIN("CHATROOM_JOIN"),
JOIN_ROOM("JOIN_ROOM"),
LEAVE_ROOM("LEAVE_ROOM"),
CONNECT_EVENT("CONNECT_EVENT"),
DISCONNECT("DISCONNECT");
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ package tw.waterballsa.gaas.spring.configs.socketio

import org.springframework.boot.context.properties.ConfigurationProperties

@ConfigurationProperties(prefix = "socketio")
@ConfigurationProperties(prefix = "socket.io")
data class SocketIOProperties (
val socketHost: String = "127.0.0.1",
val socketPort: Int = 9001){
val socketPort: Int = 9001,
){
}

0 comments on commit e808531

Please sign in to comment.