序
- 项目需要增加在线聊天的功能,采用netty-socketio实现。
总体思路 (核心就是发送事件 和监听事件)
- 后端
- 服务端监听连接事件获取前端传递的信息,建立Socket连接。
- 服务端提供自定义事件监听器,监听前端请求的事件给予反馈和逻辑处理。
- 服务端通过不同的自定义事件监听器,监听执行不同的行为。
- 服务端监听离线事件,将离线用户断开连接,释放资源。
- 前端
- 根据服务端提供的服务地址发起连接事件。
- 根据服务端自定义的事件名称发送约定格式的数据,完成交互。
- 根据服务端提供的事件名称监听服务端发起的事件
- 客户端判断离线时机,发起离线事件,释放资源。
上代码 (在idea中 Kotlin和Java可以直接转换)
- 增加依赖
implementation 'com.corundumstudio.socketio:netty-socketio:1.7.7'
- yml文件
socketio:
hostname: 0.0.0.0
port: 9090 //端口随意 区分主服务端口即可
- 参数类
import com.syxp.dlsesp.util.NoArgOpenDataClass
import org.springframework.boot.context.properties.ConfigurationProperties
@NoArgOpenDataClass
@ConfigurationProperties("socketio")
data class SocketIOProperties(
var port: Int? = null,
var hostname: String? = null,
var upgradeTimeout: Int? = null,
var pingInterval: Int? = null,
var pingTimeout: Int? = null
)
- Socket服务启动类
import com.corundumstudio.socketio.SocketIOServer
import com.syxp.dlsesp.util.LogUtils
import org.springframework.boot.CommandLineRunner
import org.springframework.core.annotation.Order
import org.springframework.stereotype.Component
@Component
@Order(1)
class SocketIORunner(private val server: SocketIOServer) : CommandLineRunner {
companion object : LogUtils()
override fun run(vararg args: String) {
log.info("SocketIO Server Starting...")
server.start()
log.info("SocketIO Server Started.")
}
}
- 服务端主要类(我删剪了部分业务)
SocketIOClient.sessionId.leastSignificantBits和 SocketIOClient.sessionId.mostSignificantBits 是两个非常重要的参数,这两个参数可以帮你构建客户端。
SocketIOServer.getClient(UUID(mostsignbits, leastsignbits)) 可以构建客户端,帮你找到你需要的客户端。这样你就可以准确推送数据给某个用户。
import com.corundumstudio.socketio.AckRequest
import com.corundumstudio.socketio.SocketIOClient
import com.corundumstudio.socketio.SocketIOServer
import com.syxp.dlsesp.util.LogUtils
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
@EnableConfigurationProperties(SocketIOProperties::class)
class SocketIOConfig(private val properties: SocketIOProperties) {
companion object : LogUtils()
@Bean
fun socketIOServer(): SocketIOServer {
val config = com.corundumstudio.socketio.Configuration()
log.debug(properties.toString())
config.hostname = properties.hostname
config.port = properties.port!!
val server = SocketIOServer(config)
server.addConnectListener { client: SocketIOClient ->
val userId = client.handshakeData.getSingleUrlParam("userId")
log.debug("Added New Connection User: $userId")
}
/**
* 指令事件监听器 监听searchClient事件
*/
server.addEventListener("searchClient", String::class.java) { client: SocketIOClient, data: String, ackRequest: AckRequest? ->
// 判断两种情况 用户找服务商 服务商找用户
// 用户找服务商 给服务商下所有客服用户推送消息
log.debug("SEARCH CLIENT EVENT DATA : {$data}")
client.sendEvent("searchClientResult", socketClientVO)
}
//监听断开连接
server.addEventListener("close", String::class.java) { client: SocketIOClient, data: String, ackRequest: AckRequest? ->
log.debug("CLOSE EVENT DATA : {$data}")
client.sendEvent("closeResult", "SUCCESS")
client.disconnect()
}
return server
}
}
前端Socket说明
Socket交互细节说明
-
前台需与后台建立Socket连接 (需要引入https://cdn.socket.io/socket.io-1.2.0.js)
var opts = { query: 'userId=用户自己的Id' }; socket = io.connect('http://IP:PORT', opts);
-
客户端发送 searchClient 事件,服务端会根据参数将需要的数据返回
socket.emit('searchClient', '{"userId":"自己的用户id","providerId":"服务商id"}');
-
客户端监听searchClientResult事件获取返回值
socket.on('searchClientResult', function (data) { console.log(data); });