mirror of
https://github.com/apple/swift-nio
synced 2026-11-27 05:04:22 +00:00
Fixed a few minor typos and some force unwraps (#259)
fix some typos, force unwraps and inconsistencies Motivation: Reviewing the code I found a few typos that hindered readability, some unnecessary force unwraps and inconsistencies in the codebase. Modifications: - The main file in NIOWebSocketServer now accepts command line arguments and binds to a passed in host and port like the other server examples do. - Minor typo fixes - removed one force unwrap Result: - The result of my change will bring the NIOWebSocketServer more inline with how the NIOHTTP1 and NIOChat servers examples are setup. - less force unwrapping - fewer typos [message edited by @weissi]
This commit is contained in:
1 parent
2a684fc1dc
commit
66e4fdfbba
15 files changed
+69
-19
No files matched your search
@@ -23,7 +23,7 @@
|
||||
/// .serverChannelOption(ChannelOptions.backlog, value: 256)
|
||||
/// .serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
|
||||
///
|
||||
/// // Set the handlers that are appled to the accepted child `Channel`s.
|
||||
/// // Set the handlers that are applied to the accepted child `Channel`s.
|
||||
/// .childChannelInitializer { channel in
|
||||
/// // Ensure we don't read faster then we can write by adding the BackPressureHandler into the pipeline.
|
||||
/// channel.pipeline.add(handler: BackPressureHandler()).then { () in
|
||||
|
||||
@@ -145,7 +145,7 @@ private func toIndex(_ value: Int) -> Index {
|
||||
/// The 'discardable bytes' are usually bytes that have already been read, they can however still be accessed using
|
||||
/// the random access methods. 'Readable bytes' are the bytes currently available to be read using the sequential
|
||||
/// access interface (`read<Type>`/`write<Type>`). Getting `writableBytes` (bytes beyond the writer index) is undefined
|
||||
/// behaviour and might yield aribitrary bytes (_not_ `0` initialised).
|
||||
/// behaviour and might yield arbitrary bytes (_not_ `0` initialised).
|
||||
///
|
||||
/// ### Slicing
|
||||
/// `ByteBuffer` supports slicing a `ByteBuffer` without copying the underlying storage.
|
||||
|
||||
@@ -99,7 +99,7 @@ extension ByteToMessageDecoder {
|
||||
/// Calls `decode` until there is nothing left to decode.
|
||||
public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) {
|
||||
var buffer = self.unwrapInboundIn(data)
|
||||
|
||||
|
||||
if self.cumulationBuffer != nil {
|
||||
self.cumulationBuffer!.write(buffer: &buffer)
|
||||
buffer = self.cumulationBuffer!
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
/// An `Error` that represents multiple errors that occurred during an operation.
|
||||
///
|
||||
/// Because SwiftNIO frequently does multiple jobs at once, it is possible some operatons out
|
||||
/// Because SwiftNIO frequently does multiple jobs at once, it is possible some operations out
|
||||
/// of a set of operations may fail. This is most noticeable with `Channel.flush` on the
|
||||
/// `DatagramChannel`, where some, but not all, of the datagram writes may fail. In this case
|
||||
/// the `flush` should accurately represent that set of possibilities. The `NIOCompositeError`
|
||||
|
||||
@@ -86,7 +86,7 @@ public protocol EventLoop: EventLoopGroup {
|
||||
/// Submit a given task to be executed by the `EventLoop`. Once the execution is complete the returned `EventLoopFuture` is notified.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - task: The closure that will be submited to the `EventLoop` for execution.
|
||||
/// - task: The closure that will be submitted to the `EventLoop` for execution.
|
||||
/// - returns: `EventLoopFuture` that is notified once the task was executed.
|
||||
func submit<T>(_ task: @escaping () throws -> T) -> EventLoopFuture<T>
|
||||
|
||||
|
||||
@@ -322,7 +322,7 @@ public struct EventLoopPromise<T> {
|
||||
///
|
||||
/// This means that for any `EventLoopFuture` that your code did not create itself (via
|
||||
/// `EventLoopPromise.futureResult`), use of `hopTo` is **strongly encouraged** to help guarantee thread-safety. It
|
||||
/// should only be elided when thread-safety is provably not needed.
|
||||
/// should only be elided when thread-safety is proved to be not needed.
|
||||
///
|
||||
/// The "thread affinity" of `EventLoopFuture`s is critical to writing safe, performant concurrent code without
|
||||
/// boilerplate. It allows you to avoid needing to write or use locks in your own code, instead using the natural
|
||||
@@ -734,7 +734,7 @@ extension EventLoopFuture {
|
||||
/// Fulfill the given `EventLoopPromise` with the results from this `EventLoopFuture`.
|
||||
///
|
||||
/// This is useful when allowing users to provide promises for you to fulfill, but
|
||||
/// when you are calling functions that return their own proimses. They allow you to
|
||||
/// when you are calling functions that return their own promises. They allow you to
|
||||
/// tidy up your computational pipelines. For example:
|
||||
///
|
||||
/// ```
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
/// Usually a `FileRegion` will allow the underlying transport to use `sendfile` to transfer its content and so allows transferring
|
||||
/// the file content without copying it into user-space at all. If the actual transport implementation really can make use of sendfile
|
||||
/// or if it will need to copy the content to user-space first and use `write` / `writev` is an implementation detail. That said
|
||||
/// using `FileRegion` is the recommend way to transfer file content if possible.
|
||||
/// using `FileRegion` is the recommended way to transfer file content if possible.
|
||||
///
|
||||
/// One important note, depending your `ChannelPipeline` setup it may not be possible to use a `FileRegion` as a `ChannelHandler` may
|
||||
/// need access to the bytes (in a `ByteBuffer`) to transform these.
|
||||
|
||||
@@ -20,7 +20,7 @@ import CNIOLinux
|
||||
/// The ids of all the cpus.
|
||||
let cpuIds: Set<Int>
|
||||
|
||||
/// Create a new instace
|
||||
/// Create a new instance
|
||||
///
|
||||
/// - arguments:
|
||||
/// - cpuIds: The `Set` of CPU ids. It must be non-empty and can not contain invalid ids.
|
||||
|
||||
@@ -89,7 +89,7 @@ public struct MarkedCircularBuffer<E>: CustomStringConvertible, AppendableCollec
|
||||
|
||||
// MARK: Marking
|
||||
|
||||
/// Marks the buffer at the current index, making the last idex in the buffer marked.
|
||||
/// Marks the buffer at the current index, making the last index in the buffer marked.
|
||||
public mutating func mark() {
|
||||
let count = self.buffer.count
|
||||
if count > 0 {
|
||||
|
||||
@@ -339,7 +339,7 @@ extension PendingDatagramWritesState {
|
||||
/// value. The most important purpose of this object is to call `sendto` or `sendmmsg` depending on the writes held and
|
||||
/// the availability of the functions.
|
||||
final class PendingDatagramWritesManager: PendingWritesManager {
|
||||
/// Storage for mmsghdr strutures. Only present on Linux because Darwin does not support
|
||||
/// Storage for mmsghdr structures. Only present on Linux because Darwin does not support
|
||||
/// gathering datagram writes.
|
||||
private var msgs: UnsafeMutableBufferPointer<MMsgHdr>
|
||||
|
||||
|
||||
@@ -127,7 +127,7 @@ final class Selector<R: Registration> {
|
||||
|
||||
/* this is technically a bad idea as we're abusing ARC to deallocate scarce resources (a file descriptor)
|
||||
for us. However, this is used for the event loop so there shouldn't be much churn.
|
||||
The reson we do this is because `self.wakeup()` may (and will!) be called on arbitrary threads. To not
|
||||
The reason we do this is because `self.wakeup()` may (and will!) be called on arbitrary threads. To not
|
||||
suffer from race conditions we would need to protect waking the selector up and closing the selector. That
|
||||
is likely to cause performance problems. By abusing ARC, we get the guarantee that there won't be any future
|
||||
wakeup calls as there are no references to this selector left. 💁
|
||||
|
||||
@@ -77,7 +77,7 @@ final class Thread {
|
||||
/// - name: The name of the `Thread` or `nil` if no specific name should be set.
|
||||
/// - body: The function to execute within the spawned `Thread`.
|
||||
static func spawnAndRun(name: String? = nil, body: @escaping (Thread) -> Void) {
|
||||
// Unfortunally the pthread_create method take a different first argument depending on if its on linux or macOS, so ensure we use the correct one.
|
||||
// Unfortunately the pthread_create method take a different first argument depending on if its on linux or macOS, so ensure we use the correct one.
|
||||
#if os(Linux)
|
||||
var pt: pthread_t = pthread_t()
|
||||
#else
|
||||
|
||||
@@ -40,7 +40,7 @@ final class LineDelimiterCodec: ByteToMessageDecoder {
|
||||
///
|
||||
/// As we are using an `MultiThreadedEventLoopGroup` that uses more then 1 thread we need to ensure proper
|
||||
/// synchronization on the shared state in the `ChatHandler` (as the same instance is shared across
|
||||
/// child `Channel`s). For this a serial `DispatchQueue` is used when we modify the shared state (the `Dictonary`).
|
||||
/// child `Channel`s). For this a serial `DispatchQueue` is used when we modify the shared state (the `Dictionary`).
|
||||
/// As `ChannelHandlerContext` is not thread-safe we need to ensure we only operate on the `Channel` itself while
|
||||
/// `Dispatch` executed the submitted block.
|
||||
final class ChatHandler: ChannelInboundHandler {
|
||||
@@ -119,7 +119,7 @@ let bootstrap = ServerBootstrap(group: group)
|
||||
.serverChannelOption(ChannelOptions.backlog, value: 256)
|
||||
.serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
|
||||
|
||||
// Set the handlers that are appled to the accepted Channels
|
||||
// Set the handlers that are applied to the accepted Channels
|
||||
.childChannelInitializer { channel in
|
||||
// Add handler that will buffer data until a \n is received
|
||||
channel.pipeline.add(handler: LineDelimiterCodec()).then { v in
|
||||
@@ -177,7 +177,11 @@ let channel = try { () -> Channel in
|
||||
}
|
||||
}()
|
||||
|
||||
print("ChatServer started and listening on \(channel.localAddress!)")
|
||||
if let localAddress = channel.localAddress {
|
||||
print("ChatServer started and listening on \(localAddress)")
|
||||
} else {
|
||||
print("ChatServer started but the address could not be determined.")
|
||||
}
|
||||
|
||||
// This will never unblock as we don't close the ServerChannel.
|
||||
try channel.closeFuture.wait()
|
||||
|
||||
@@ -498,7 +498,11 @@ let channel = try { () -> Channel in
|
||||
}
|
||||
}()
|
||||
|
||||
print("Server started and listening on \(channel.localAddress!), htdocs path \(htdocs)")
|
||||
if let localAddress = channel.localAddress {
|
||||
print("Server started and listening on \(localAddress), htdocs path \(htdocs)")
|
||||
} else {
|
||||
print("Server started but the address could not be determined, htdocs path \(htdocs)")
|
||||
}
|
||||
|
||||
// This will never unblock as we don't close the ServerChannel
|
||||
try channel.closeFuture.wait()
|
||||
|
||||
@@ -224,9 +224,51 @@ defer {
|
||||
try! group.syncShutdownGracefully()
|
||||
}
|
||||
|
||||
// First argument is the program path
|
||||
let arguments = CommandLine.arguments
|
||||
let arg1 = arguments.dropFirst().first
|
||||
let arg2 = arguments.dropFirst(2).first
|
||||
|
||||
let channel = try! bootstrap.bind(host: "localhost", port: 8888).wait()
|
||||
print("Server started and listening on \(channel.localAddress!)")
|
||||
let defaultHost = "localhost"
|
||||
let defaultPort = 8888
|
||||
|
||||
enum BindTo {
|
||||
case ip(host: String, port: Int)
|
||||
case unixDomainSocket(path: String)
|
||||
}
|
||||
|
||||
let bindTarget: BindTo
|
||||
switch (arg1, arg1.flatMap(Int.init), arg2.flatMap(Int.init)) {
|
||||
case (.some(let h), _ , .some(let p)):
|
||||
/* we got two arguments, let's interpret that as host and port */
|
||||
bindTarget = .ip(host: h, port: p)
|
||||
|
||||
case (let portString?, .none, _):
|
||||
// Couldn't parse as number, expecting unix domain socket path.
|
||||
bindTarget = .unixDomainSocket(path: portString)
|
||||
|
||||
case (_, let p?, _):
|
||||
// Only one argument --> port.
|
||||
bindTarget = .ip(host: defaultHost, port: p)
|
||||
|
||||
default:
|
||||
bindTarget = .ip(host: defaultHost, port: defaultPort)
|
||||
}
|
||||
|
||||
let channel = try { () -> Channel in
|
||||
switch bindTarget {
|
||||
case .ip(let host, let port):
|
||||
return try bootstrap.bind(host: host, port: port).wait()
|
||||
case .unixDomainSocket(let path):
|
||||
return try bootstrap.bind(unixDomainSocketPath: path).wait()
|
||||
}
|
||||
}()
|
||||
|
||||
if let localAddress = channel.localAddress {
|
||||
print("Server started and listening on \(localAddress)")
|
||||
} else {
|
||||
print("Server started but the address could not be determined.")
|
||||
}
|
||||
|
||||
// This will never unblock as we don't close the ServerChannel
|
||||
try channel.closeFuture.wait()
|
||||
|
||||
Reference in new issue
Block a user