Skip to content

Commit

Permalink
Add --vsock flag to HelloWorldClient and HelloWorldServer
Browse files Browse the repository at this point in the history
  • Loading branch information
simonjbeaumont committed Jul 28, 2023
1 parent b24c0d3 commit 12789c1
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
15 changes: 14 additions & 1 deletion Sources/Examples/HelloWorld/Client/HelloWorldClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ struct HelloWorld: AsyncParsableCommand {
@Option(help: "The port to connect to")
var port: Int = 1234

@Flag(help: "Use local vsock socket")
var vsock = false

@Argument(help: "The name to greet")
var name: String?

Expand All @@ -40,8 +43,18 @@ struct HelloWorld: AsyncParsableCommand {
}

// Configure the channel, we're not using TLS so the connection is `insecure`.
let target: ConnectionTarget
if vsock {
#if canImport(Darwin)
target = .vsockAddress(.init(cid: .any, port: .init(self.port)))
#else
target = .vsockAddress(.init(cid: .local, port: .init(self.port)))
#endif
} else {
target = .host("localhost", port: self.port)
}
let channel = try GRPCChannelPool.with(
target: .host("localhost", port: self.port),
target: target,
transportSecurity: .plaintext,
eventLoopGroup: group
)
Expand Down
20 changes: 14 additions & 6 deletions Sources/Examples/HelloWorld/Server/HelloWorldServer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,27 @@ struct HelloWorld: AsyncParsableCommand {
@Option(help: "The port to listen on for new connections")
var port = 1234

@Flag(help: "Use local vsock socket")
var vsock = false

func run() async throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
try! group.syncShutdownGracefully()
}

// Start the server and print its address once it has started.
let server = try await Server.insecure(group: group)
.withServiceProviders([GreeterProvider()])
.bind(host: "localhost", port: self.port)
.get()
let serverBuilder = Server.insecure(group: group).withServiceProviders([GreeterProvider()])

print("server started on port \(server.channel.localAddress!.port!)")
// Start the server and print its address once it has started.
let server: Server
if self.vsock {
let vsockAddress = VsockAddress(cid: .any, port: .init(self.port))
server = try await serverBuilder.bind(vsockAddress: vsockAddress).get()
print("server started on \(vsockAddress)")
} else {
server = try await serverBuilder.bind(host: "localhost", port: self.port).get()
print("server started on port \(server.channel.localAddress!.port!)")
}

// Wait on the server's `onClose` future to stop the program from exiting.
try await server.onClose.get()
Expand Down

0 comments on commit 12789c1

Please sign in to comment.