@@ -7,6 +7,7 @@ Ask questions in our <a href="https://slackin-on-edge.herokuapp.com">Slack</a> c
7
7
8
8
# Edge
9
9
10
+ [ ![ Build Status] ( https://travis-ci.org/SwiftOnEdge/Edge.svg?branch=master )] ( https://travis-ci.org/SwiftOnEdge/Edge )
10
11
[ ![ Slack Status] ( https://slackin-on-edge.herokuapp.com/badge.svg )] ( https://slackin-on-edge.herokuapp.com )
11
12
12
13
#### Node
@@ -45,18 +46,56 @@ let package = Package(
45
46
46
47
# Usage
47
48
49
+ ### HTTP
50
+ ``` swift
51
+ import Edge
52
+ import Foundation
53
+
54
+ func handleRequest (request : Request) -> Response {
55
+ print (String (bytes : request.body , encoding : .utf8 )! )
56
+ let responseBodyObject = [" message" : " Message received!" ]
57
+ let responseBody = Array (try ! JSONSerialization.data (withJSONObject : responseBodyObject))
58
+
59
+ return Response (
60
+ version : Version (major : 1 , minor : 1 ),
61
+ status : .ok ,
62
+ rawHeaders : [" Content-Type: application/json" ],
63
+ body : responseBody
64
+ )
65
+ }
66
+
67
+ let server = HTTP.Server ()
68
+ server.listen (host : " 0.0.0.0" , port : 3000 ).startWithNext { client in
69
+
70
+ let requestStream = client.read ()
71
+ requestStream.map (transform : handleRequest).onNext { response in
72
+ client.write (response)
73
+ }
74
+
75
+ requestStream.onFailed { clientError in
76
+ print (" Oh no, there was an error! \( clientError ) " )
77
+ }
78
+
79
+ requestStream.onCompleted {
80
+ print (" Goodbye \( client ) !" )
81
+ }
82
+
83
+ requestStream.start ()
84
+ }
85
+ ```
86
+
48
87
### TCP
49
88
``` Swift
50
89
51
90
import Edge
52
91
import Foundation
53
92
54
93
let server = try ! TCP.Server ()
55
- try server.bind (host : " 0.0.0.0" , port : 50000 )
94
+ try ! server.bind (host : " 0.0.0.0" , port : 50000 )
56
95
57
96
server.listen ().startWithNext { connection in
58
- let read = connection.read ()
59
- let strings = read .map { String (bytes : $0 , encoding : .utf8 )! }
97
+ let byteStream = connection.read ()
98
+ let strings = byteStream .map { String (bytes : $0 , encoding : .utf8 )! }
60
99
61
100
strings.onNext { message in
62
101
print (" Client \( connection ) says \" \( message ) \" !" )
@@ -70,7 +109,7 @@ server.listen().startWithNext { connection in
70
109
print (" Goodbye \( connection ) !" )
71
110
}
72
111
73
- read .start ()
112
+ byteStream .start ()
74
113
}
75
114
76
115
RunLoop.runAll ()
0 commit comments