|
1 | | -# kmp-web-sockets |
2 | | -Kotlin Multiplatform Library for Web Sockets |
| 1 | +<img alt="Wannaverse Logo" src="./assets/logo.png" width="288"/> |
| 2 | + |
| 3 | +[](https://github.com/WannaverseOfficial/kmp-web-sockets/actions) |
| 4 | +[](https://github.com/WannaverseOfficial/kmp-web-sockets/actions) |
| 5 | + |
| 6 | +# Web Socket Client |
| 7 | + |
| 8 | +A Kotlin Multiplatform web socket library for Android, iOS and Desktop. |
| 9 | + |
| 10 | +## ✅ Supported Platform |
| 11 | + |
| 12 | +| Platform | Supported | |
| 13 | +|:---------|:----------| |
| 14 | +| Android | ✔️ | |
| 15 | +| iOS | ✔️ | |
| 16 | +| Desktop | ✔️ | |
| 17 | +| Web | ❌️ | |
| 18 | + |
| 19 | +## 🚀 Installation |
| 20 | +See the releases section of this repository for the latest version. |
| 21 | + |
| 22 | +To your `build.gradle` under `commonMain.dependencies` add: |
| 23 | + |
| 24 | +```kotlin |
| 25 | +implementation "com.wannaverse:kmp-web-sockets:<version>" |
| 26 | +``` |
| 27 | + |
| 28 | +## Usage |
| 29 | + |
| 30 | +[KDocs](https://wannaverseofficial.github.io/kmp-web-sockets/) |
| 31 | + |
| 32 | +Below is a sample code that you may use. |
| 33 | + |
| 34 | +Example `ViewModel`: |
| 35 | +```kotlin |
| 36 | +class AppViewModel : ViewModel() { |
| 37 | + private var wsManager: WebSocketManager? = null |
| 38 | + |
| 39 | + var isLoading = mutableStateOf(false) |
| 40 | + var connected = mutableStateOf(false) |
| 41 | + val websocketURL = mutableStateOf("wss://ws.ifelse.io") |
| 42 | + val messages = mutableStateListOf<String>() |
| 43 | + |
| 44 | + fun connectToServer() = viewModelScope.launch { |
| 45 | + isLoading.value = true |
| 46 | + |
| 47 | + if (wsManager == null) { |
| 48 | + wsManager = WebSocketManager(websocketURL.value) |
| 49 | + wsManager?.incomingMessages?.onEach { message -> |
| 50 | + messages.add("Server: $message") |
| 51 | + }?.launchIn(viewModelScope) |
| 52 | + } |
| 53 | + |
| 54 | + wsManager?.connect() |
| 55 | + |
| 56 | + isLoading.value = false |
| 57 | + connected.value = true |
| 58 | + } |
| 59 | + |
| 60 | + fun sendMessage(message: String) { |
| 61 | + messages.add("You: $message") |
| 62 | + wsManager?.send(message) |
| 63 | + } |
| 64 | + |
| 65 | + fun disconnect() { |
| 66 | + connected.value = false |
| 67 | + wsManager?.disconnect() |
| 68 | + } |
| 69 | + |
| 70 | + override fun onCleared() { |
| 71 | + connected.value = false |
| 72 | + super.onCleared() |
| 73 | + wsManager?.clear() |
| 74 | + } |
| 75 | +} |
| 76 | +``` |
| 77 | + |
| 78 | +## 📄 License |
| 79 | +MIT LICENSE. See [LICENSE](./LICENSE) for details. |
| 80 | + |
| 81 | +## 🙌 Contributing |
| 82 | +Pull requests and feature requests are welcome! |
| 83 | +If you encounter any issues, feel free to open an issue. |
0 commit comments