mirror of
https://github.com/apple/swift-nio
synced 2026-11-24 04:37:54 +00:00
Motivation:
There are multiple sub-optimal ByteBuffer creation patterns that occur
in the wild. Most often they happen when people don't actually have
access to a `Channel` just want to "convert" a `String` into a
`ByteBuffer`. To do this, they are forced to type
var buffer = ByteBufferAllocator().buffer(capacity: string.utf8.count)
buffer.writeString(string)
Sometimes, they don't get the capacity calculation right or just put a
`0`.
Similar problems happen if NIO users want to cache a ByteBuffer in their
`ChannelHandler`. You will then find this code:
```swift
if self.buffer == nil {
self.buffer = receivedBuffer
} else {
var receivedBuffer = receivedBuffer
self.buffer!.writeBuffer(&receivedBuffer)
}
```
And lastly, sometimes people want to append one `ByteBuffer` to another
without mutating the appendee. That's also cumbersome because we only
support a mutable version of `writeBuffer`.
Modifications:
- add `ByteBuffer` convenience initialisers
- add convenience `writeBuffer` methods to `Optional<ByteBuffer>`
- add `writeBufferImmutable` which doesn't mutate the appendee.
Result:
More convenience.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
103 lines
3.2 KiB
Swift
103 lines
3.2 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This source file is part of the SwiftNIO open source project
|
|
//
|
|
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
|
|
// Licensed under Apache License v2.0
|
|
//
|
|
// See LICENSE.txt for license information
|
|
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
|
//
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
import NIO
|
|
|
|
private final class ChatHandler: ChannelInboundHandler {
|
|
public typealias InboundIn = ByteBuffer
|
|
public typealias OutboundOut = ByteBuffer
|
|
|
|
private func printByte(_ byte: UInt8) {
|
|
#if os(Android)
|
|
print(Character(UnicodeScalar(byte)), terminator:"")
|
|
#else
|
|
fputc(Int32(byte), stdout)
|
|
#endif
|
|
}
|
|
|
|
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
|
|
var buffer = self.unwrapInboundIn(data)
|
|
while let byte: UInt8 = buffer.readInteger() {
|
|
printByte(byte)
|
|
}
|
|
}
|
|
|
|
public func errorCaught(context: ChannelHandlerContext, error: Error) {
|
|
print("error: ", error)
|
|
|
|
// As we are not really interested getting notified on success or failure we just pass nil as promise to
|
|
// reduce allocations.
|
|
context.close(promise: nil)
|
|
}
|
|
}
|
|
|
|
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
|
let bootstrap = ClientBootstrap(group: group)
|
|
// Enable SO_REUSEADDR.
|
|
.channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
|
|
.channelInitializer { channel in
|
|
channel.pipeline.addHandler(ChatHandler())
|
|
}
|
|
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 defaultHost = "::1"
|
|
let defaultPort = 9999
|
|
|
|
enum ConnectTo {
|
|
case ip(host: String, port: Int)
|
|
case unixDomainSocket(path: String)
|
|
}
|
|
|
|
let connectTarget: ConnectTo
|
|
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 */
|
|
connectTarget = .ip(host: h, port: p)
|
|
case (.some(let portString), .none, _):
|
|
/* couldn't parse as number, expecting unix domain socket path */
|
|
connectTarget = .unixDomainSocket(path: portString)
|
|
case (_, .some(let p), _):
|
|
/* only one argument --> port */
|
|
connectTarget = .ip(host: defaultHost, port: p)
|
|
default:
|
|
connectTarget = .ip(host: defaultHost, port: defaultPort)
|
|
}
|
|
|
|
let channel = try { () -> Channel in
|
|
switch connectTarget {
|
|
case .ip(let host, let port):
|
|
return try bootstrap.connect(host: host, port: port).wait()
|
|
case .unixDomainSocket(let path):
|
|
return try bootstrap.connect(unixDomainSocketPath: path).wait()
|
|
}
|
|
}()
|
|
|
|
print("ChatClient connected to ChatServer: \(channel.remoteAddress!), happy chatting\n. Press ^D to exit.")
|
|
|
|
while let line = readLine(strippingNewline: false) {
|
|
let buffer = channel.allocator.buffer(string: line)
|
|
try! channel.writeAndFlush(buffer).wait()
|
|
}
|
|
|
|
// EOF, close connect
|
|
try! channel.close().wait()
|
|
|
|
print("ChatClient closed")
|