Skip to content

feat: implement HybridWebSocket on Android #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Nov 2, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ npm install react-native-fast-ws --save

### TODOs

- Provide Android support
- Document things not implemented in spec, or different from spec
- Fix outstanding (and known) issues
- Figure out a better name and logo
Expand Down
6 changes: 4 additions & 2 deletions example/App.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useCallback, useState } from 'react'
import { ActivityIndicator, Button, StyleSheet, Text, View } from 'react-native'
import { ActivityIndicator, Button, Platform, StyleSheet, Text, View } from 'react-native'
import { WebSocket as FastWebSocket } from 'react-native-fast-ws'

type Result = {
Expand Down Expand Up @@ -122,7 +122,9 @@ const testWebsocketMessages = async (opts: {
incomingTime: number
}> =>
new Promise((resolve) => {
const inst = new opts.Ws('ws://localhost:3000')
const inst = new opts.Ws(
Platform.OS === 'android' ? 'ws://10.0.2.2:3000' : 'ws://localhost:3000'
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should probably move it to some config file

)

let outgoingTime: number
let incomingTime: number
Expand Down
3 changes: 3 additions & 0 deletions packages/react-native-fast-ws/android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,9 @@ dependencies {

// Add a dependency on NitroModules
implementation project(":react-native-nitro-modules")

// Let's use whatever React Native uses right now to avoid duplicates
implementation "com.squareup.okhttp3:okhttp:+"
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if this is correct, have to check 🤣

}

if (isNewArchitectureEnabled()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,49 +1,99 @@
package com.margelo.nitro.websocket

import com.margelo.nitro.core.ArrayBuffer
import okhttp3.*
import okio.ByteString
import okio.ByteString.Companion.toByteString
import java.util.concurrent.TimeUnit

class HybridWebSocket(url: String, protocols: Array<String>) : HybridWebSocketSpec() {
override fun send(message: String) {
TODO("Not implemented")
}
private var onOpenCallback: ((String) -> Unit)? = null
private var onCloseCallback: ((Double, String) -> Unit)? = null
private var onErrorCallback: ((String) -> Unit)? = null
private var onMessageCallback: ((String) -> Unit)? = null
private var onArrayBufferCallback: ((ArrayBuffer) -> Unit)? = null

override fun sendArrayBuffer(buffer: ArrayBuffer) {
TODO("Not implemented")
private val client = OkHttpClient.Builder()
.readTimeout(0, TimeUnit.MILLISECONDS) // Disable timeouts
.build()

private var webSocket: WebSocket? = null

private val listener = object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
val protocol = response.header("Sec-WebSocket-Protocol") ?: ""
onOpenCallback?.invoke(protocol)
}

override fun onMessage(webSocket: WebSocket, text: String) {
onMessageCallback?.invoke(text)
}

override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
val buffer = ArrayBuffer.allocate(bytes.size)
buffer.getBuffer(false).put(bytes.toByteArray())
onArrayBufferCallback?.invoke(buffer)
}

override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
onCloseCallback?.invoke(code.toDouble(), reason)
webSocket.close(code, reason)
}

override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
onErrorCallback?.invoke(t.message ?: "WebSocket error")
}
}

private val request = Request.Builder()
.url(url)
.apply {
if (protocols.isNotEmpty()) {
header("Sec-WebSocket-Protocol", protocols.joinToString(", "))
}
}
.build()

override fun connect() {
TODO("Not implemented")
webSocket = client.newWebSocket(request, listener)
}

override fun close() {
TODO("Not implemented")
webSocket?.close(1000, null)
}

override fun send(message: String) {
webSocket?.send(message)
}

override fun sendArrayBuffer(buffer: ArrayBuffer) {
webSocket?.send(buffer.getBuffer(false).toByteString())
}

override fun ping() {
TODO("Not implemented")
webSocket?.send(ByteString.EMPTY)
}

override fun onOpen(callback: (selectedProtocol: String) -> Unit) {
TODO("Not implemented")
onOpenCallback = callback
}

override fun onClose(callback: (code: Double, reason: String) -> Unit) {
TODO("Not implemented")
onCloseCallback = callback
}

override fun onError(callback: (error: String) -> Unit) {
TODO("Not implemented")
onErrorCallback = callback
}

override fun onMessage(callback: (message: String) -> Unit) {
TODO("Not implemented")
onMessageCallback = callback
}

override fun onArrayBuffer(callback: (buffer: ArrayBuffer) -> Unit) {
TODO("Not implemented")
onArrayBufferCallback = callback
}

override val memorySize: Long
get() = 0L

get() = 0L // Implement proper memory calculation if needed
}
2 changes: 1 addition & 1 deletion packages/react-native-fast-ws/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
import { NitroModules } from 'react-native-nitro-modules'

import { Blob } from './blob'
import { WebSocket as HybridWebSocket, WebSocketManager } from './WebSocket.nitro'
import { WebSocket as HybridWebSocket, WebSocketManager } from './spec.nitro'

const manager = NitroModules.createHybridObject<WebSocketManager>('WebSocketManager')

Expand Down