Merge: src/model/model_index: model index uses BKTree
[nit.git] / lib / libevent / libevent_example.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Minimal usage example of libevent
16 module libevent_example is example
17
18 import libevent
19
20 # Factory creating instances of `EchoConnection` to handle new connections
21 class MyFactory
22 super ConnectionFactory
23
24 redef fun spawn_connection(buf, address)
25 do
26 return new EchoConnection(buf)
27 end
28 end
29
30 # Connection echoing data received from clients back at them
31 class EchoConnection
32 super Connection
33
34 redef fun read_callback(content)
35 do
36 print "Received: {content}"
37 write content
38 end
39 end
40
41 # Skip the actual execution when testing
42 if "NIT_TESTING".environ == "true" then exit 0
43
44 # Setup libevent system
45 var event_base = new NativeEventBase
46 var factory = new MyFactory(event_base)
47
48 # Open a TCP socket for listening
49 factory.bind_tcp("localhost", 8888)
50
51 # Open a UNIX domain socket for listening
52 factory.bind_unix("/tmp/my.sck")
53
54 # Launch event loop
55 event_base.dispatch
56
57 event_base.free