我想在Kotlin中为android创建一个应用程序,并且我正在使用Socket io从服务器获取数据。问题是,我在任何地方都找不到如何编写“ socket.on”方法以及如何对数据进行处理的方法,只有Java中只有“ .emit”方法。你能帮我吗?
答案 0 :(得分:0)
我已经这样做了:
单身人士:
Person(name=John, age=30, telephone=Telephone(codeArea=16, number=1111-2222))
为我服务:
class WebSocket{
private var mSocket: Socket? = null
companion object {
@Volatile
private var INSTANCE: WebSocket? = null
fun getInstance() =
INSTANCE ?: synchronized(this) {
INSTANCE ?: WebSocket().also {
INSTANCE = it
}
}
}
fun createSocket(id:String) {
val mUrl = "https://myserverurl"
try {
val opts = IO.Options()
opts.forceNew = true
opts.reconnection = true
opts.secure = true
opts.query = "id=${id}"
mSocket = IO.socket(mUrl,opts)
mSocket!!.connect()
} catch (e: URISyntaxException) {
e.printStackTrace()
}
}
fun onNewMessage(cb:(fromId:String,
toId:String,
fromDeviceId:String,
senderName:String,
receiverName:String,
message:String,
productId:String,
timestamp:String ) -> Unit): Emitter.Listener {
return Emitter.Listener { args ->
val data = args[0] as JSONObject
val senderName = data.getString("sender_name")
val receiverName = data.getString("receiver_name")
val message = data.getString("message")
val fromId = data.getString("from_id")
val toId = data.getString("to_id")
val fromDeviceId = data.getString("from_device_id")
val productId = data.getString("product_id")
val timestamp = data.getString("timestamp")
cb( fromId,
toId,
fromDeviceId,
senderName,
receiverName,
message,
productId,
timestamp )
}
}
fun getSocket():Socket? {
return mSocket
}
}
通过这种方式,您可以调用WebSocket.getInstance().createSocket(userId!!)
val io = WebSocket.getInstance().getSocket()
//val notifications = NotificationsHandler()
io!!.on("message",
WebSocket.getInstance().onNewMessage { fromId, toId, fromDeviceId, senderName, receiverName, message, productId, timestamp ->
//here you handle fromId, toId, fromDeviceId, senderName, receiverName, message, productId, timestamp
})
(在创建WebSocket.getInstance().getSocket()
之后),并且套接字可以在任何活动中使用。