scoop:scoop.http.asyncio:0.1.0
src/websocket/send.scoop
Selected production source · src/websocket/send.scoop
1
package scoop.http.asyncio3
import scoop.asyncio.*4
import scoop.http.*5
import scoop.platform.memory.NativeByteBuffer7
internal suspend fun sendWsBytes(state: WsState, type: WebSocketMessageType, bytes: Array<Byte>, compress: Boolean) {8
wsOperation<WsOutgoing, Unit>(state, false, { beginWsMessage(state, type, compress) }, suspend { message ->9
NativeByteBuffer.allocate(state.options.outgoingFrameBytes).use suspend { buffer ->10
var offset = 0L11
while (offset < bytes.size) {12
buffer.clear()13
val count = if (bytes.size - offset < buffer.capacity) bytes.size - offset else buffer.capacity14
buffer.writeBytes(bytes, offset, count)15
writeWsMessage(state, message, buffer, count)16
offset += count17
}18
finishWsMessage(state, message)19
}20
})21
}23
internal suspend fun sendWsSource(state: WsState, type: WebSocketMessageType, source: AsyncByteSource, compress: Boolean) {24
wsOperation<WsOutgoing, Unit>(state, false, { beginWsMessage(state, type, compress) }, suspend { message ->25
runWsSource<Unit>(state) suspend {26
NativeByteBuffer.allocate(state.options.outgoingFrameBytes).use suspend { buffer ->27
while (true) {28
state.lock.withLock { wsOpen(state) }29
buffer.clear()30
val requested = buffer.writableBytes31
val count = source.readInto(buffer, requested)32
httpProgress(count, requested)33
if (buffer.readPosition != 0L || buffer.writePosition != count)34
throw IllegalStateException(Some("WebSocket source progress does not match its buffer"))35
if (count == 0L) break36
writeWsMessage(state, message, buffer, count)37
}38
finishWsMessage(state, message)39
}40
}41
})42
}