forked from KyoheiG3/grpc-swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEchoProvider.swift
81 lines (77 loc) · 2.7 KB
/
EchoProvider.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
* Copyright 2016, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Dispatch
import Foundation
import gRPC
class EchoProvider: Echo_EchoProvider {
// get returns requests as they were received.
func get(request: Echo_EchoRequest, session _: Echo_EchoGetSession) throws -> Echo_EchoResponse {
var response = Echo_EchoResponse()
response.text = "Swift echo get: " + request.text
return response
}
// expand splits a request into words and returns each word in a separate message.
func expand(request: Echo_EchoRequest, session: Echo_EchoExpandSession) throws {
let parts = request.text.components(separatedBy: " ")
var i = 0
for part in parts {
var response = Echo_EchoResponse()
response.text = "Swift echo expand (\(i)): \(part)"
let sem = DispatchSemaphore(value: 0)
try session.send(response) { _ in sem.signal() }
_ = sem.wait(timeout: DispatchTime.distantFuture)
i += 1
sleep(1)
}
}
// collect collects a sequence of messages and returns them concatenated when the caller closes.
func collect(session: Echo_EchoCollectSession) throws {
var parts: [String] = []
while true {
do {
let request = try session.receive()
parts.append(request.text)
} catch ServerError.endOfStream {
break
} catch (let error) {
print("\(error)")
}
}
var response = Echo_EchoResponse()
response.text = "Swift echo collect: " + parts.joined(separator: " ")
try session.sendAndClose(response)
}
// update streams back messages as they are received in an input stream.
func update(session: Echo_EchoUpdateSession) throws {
var count = 0
while true {
do {
let request = try session.receive()
count += 1
var response = Echo_EchoResponse()
response.text = "Swift echo update (\(count)): \(request.text)"
let sem = DispatchSemaphore(value: 0)
try session.send(response) { _ in sem.signal() }
_ = sem.wait(timeout: DispatchTime.distantFuture)
} catch ServerError.endOfStream {
break
} catch (let error) {
print("\(error)")
}
}
try session.close()
}
}