本文介绍了如何在 kotlin 中使用套接字 IO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在我的 kotlin 应用程序中初始化套接字 IO.
我的问题在这里:
私有变量 mSocket:套接字?= 空{尝试 {mSocket = IO.socket("http://chat.socket.io")} catch (URISyntaxException e) {}}
导入 com.github.nkzawa.socketio.client.IO
无法识别
解决方案
我搜索了更多,找到了这个解决方案:
你像这样连接你的 ws:
val opts = IO.Options()opts.path = "/path/to/ws"opts.transsports = arrayOf(WebSocket.NAME)//将传输设置为 'websocket' 而不是 'polling'val webSocket = IO.socket("http(s)://your.ip.here", opts)webSocket.connect().on(Socket.EVENT_CONNECT) {//在这里做你的事情}.on("foo") { 参数 ->//在接收到foo"事件时做一些事情//'parameters' 是你发送的所有参数的数组//在这里做你的事情}
如果你想发出一个事件,你会调用:
webSocket.emit("foo", "bar")//以 'bar' 作为参数发出一个 'foo' 事件
您将需要使用
import com.github.nkzawa.socketio.client.IO;导入 com.github.nkzawa.socketio.client.Socket;
所以一定要把对应的库添加到你的build.gradle
依赖项{...实现 'com.github.nkzawa:socket.io-client:0.6.0'}
I want to initialize socket IO in my kotlin app.
my problem is here :
private var mSocket: Socket? = null
{
try {
mSocket = IO.socket("http://chat.socket.io")
} catch (URISyntaxException e) {
}
}
cant recognize
解决方案
I searched for this some more and found this solution:
You connect your ws like this:
val opts = IO.Options()
opts.path = "/path/to/ws"
opts.transports = arrayOf(WebSocket.NAME) // Set the transfer to 'websocket' instead of 'polling'
val webSocket = IO.socket("http(s)://your.ip.here", opts)
webSocket.connect()
.on(Socket.EVENT_CONNECT) {
// Do your stuff here
}
.on("foo") { parameters -> // do something on recieving a 'foo' event
// 'parameters' is an Array of all parameters you sent
// Do your stuff here
}
If you want to emit an event, you'll call:
webSocket.emit("foo", "bar") // Emits a 'foo' event with 'bar' as a parameter
You will need to use
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
so be sure to add the corresponding libraries to your build.gradle
dependencies {
...
implementation 'com.github.nkzawa:socket.io-client:0.6.0'
}
这篇关于如何在 kotlin 中使用套接字 IO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!