1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2013 Matthieu Lucas <lucasmatthieu@gmail.com>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
20 private import socket_c
21 intrude import standard
::stream
23 # A general TCP socket, either a `TCPStream` or a `TCPServer`
27 private var socket
: NativeSocket is noinit
29 # Port used by the socket
32 # IPv4 address to which `self` is connected
34 # Formatted as xxx.xxx.xxx.xxx.
35 var address
: String is noinit
37 # Is this socket closed?
41 # Simple communication stream with a remote socket
48 # Real canonical name of the host to which `self` is connected
51 private var addrin
: NativeSocketAddrIn is noinit
53 redef var end_reached
= false
55 # TODO make init private
57 # Creates a socket connection to host `host` on port `port`
58 init connect
(host
: String, port
: Int)
60 _buffer
= new FlatBuffer
62 socket
= new NativeSocket.socket
(new NativeSocketAddressFamilies.af_inet
,
63 new NativeSocketTypes.sock_stream
, new NativeSocketProtocolFamilies.pf_null
)
64 if socket
.address_is_null
then
69 if not socket
.setsockopt
(new NativeSocketOptLevels.socket
, new NativeSocketOptNames.reuseaddr
, 1) then
74 var hostname
= socket
.gethostbyname
(host
)
75 addrin
= new NativeSocketAddrIn.with_hostent
(hostname
, port
)
77 address
= addrin
.address
78 init(addrin
.port
, hostname
.h_name
)
80 closed
= not internal_connect
84 # Creates a client socket, this is meant to be used by accept only
85 private init server_side
(h
: SocketAcceptResult)
87 _buffer
= new FlatBuffer
91 address
= addrin
.address
93 init(addrin
.port
, address
)
96 redef fun poll_in
do return ready_to_read
(0)
98 # Returns an array containing an enum of the events ready to be read
100 # event_types : Combination of several event types to watch
102 # timeout : Time in milliseconds before stopping listening for events on this socket
103 private fun pollin
(event_types
: Array[NativeSocketPollValues], timeout
: Int): Array[NativeSocketPollValues] do
104 if end_reached
then return new Array[NativeSocketPollValues]
105 return socket
.socket_poll
(new PollFD(socket
.descriptor
, event_types
), timeout
)
108 # Easier use of pollin to check for something to read on all channels of any priority
110 # timeout : Time in milliseconds before stopping to wait for events
111 fun ready_to_read
(timeout
: Int): Bool
113 if _buffer_pos
< _buffer
.length
then return true
114 if end_reached
then return false
115 var events
= [new NativeSocketPollValues.pollin
]
116 return pollin
(events
, timeout
).length
!= 0
119 # Checks if the socket still is connected
122 if closed
then return false
123 var events
= [new NativeSocketPollValues.pollhup
, new NativeSocketPollValues.pollerr
]
124 if pollin
(events
, 0).length
== 0 then
132 redef fun is_writable
do return not end_reached
134 # Establishes a connection to socket addrin
136 # REQUIRES : not self.end_reached
137 private fun internal_connect
: Bool
140 return socket
.connect
(addrin
) >= 0
143 # If socket.end_reached, nothing will happen
144 redef fun write
(msg
: Text)
146 if closed
then return
147 socket
.write
(msg
.to_s
)
150 fun write_ln
(msg
: Text)
152 if end_reached
then return
157 redef fun fill_buffer
161 if not connected
then return
162 var read
= socket
.read
163 if read
.length
== 0 then
172 if closed
then return
173 if socket
.close
>= 0 then
179 # Send the data present in the socket buffer
182 if not socket
.setsockopt
(new NativeSocketOptLevels.tcp
, new NativeSocketOptNames.tcp_nodelay
, 1) or
183 not socket
.setsockopt
(new NativeSocketOptLevels.tcp
, new NativeSocketOptNames.tcp_nodelay
, 0) then
189 # A socket listening on a given `port` for incomming connections
191 # Create streams to communicate with clients using `accept`.
195 private var addrin
: NativeSocketAddrIn is noinit
197 # Create and bind a listening server socket on port `port`
200 socket
= new NativeSocket.socket
(new NativeSocketAddressFamilies.af_inet
,
201 new NativeSocketTypes.sock_stream
, new NativeSocketProtocolFamilies.pf_null
)
202 assert not socket
.address_is_null
203 if not socket
.setsockopt
(new NativeSocketOptLevels.socket
, new NativeSocketOptNames.reuseaddr
, 1) then
207 addrin
= new NativeSocketAddrIn.with
(port
, new NativeSocketAddressFamilies.af_inet
)
208 address
= addrin
.address
214 # Associates the socket to a local address and port
216 # Returns whether the socket has been be bound.
217 private fun bind
: Bool do
218 return socket
.bind
(addrin
) >= 0
221 # Sets the socket as ready to accept incoming connections, `size` is the maximum number of queued clients
223 # Returns `true` if the socket could be set, `false` otherwise
224 fun listen
(size
: Int): Bool do
225 return socket
.listen
(size
) >= 0
228 # Accepts an incoming connection from a client
230 # Create and return a new socket to the client. May return null if not
231 # `blocking` and there's no waiting clients, or upon an interruption
232 # (whether `blocking` or not).
234 # Require: not closed
235 fun accept
: nullable TCPStream
238 var native
= socket
.accept
239 if native
== null then return null
240 return new TCPStream.server_side
(native
)
243 # Set whether calls to `accept` are blocking
244 fun blocking
=(value
: Bool)
246 # We use the opposite from the native version as the native API
247 # is closer to the C API. In the Nity API, we use a positive version
249 socket
.non_blocking
= not value
255 # FIXME unify with `SocketStream::close` when we can use qualified names
257 if closed
then return
258 if socket
.close
>= 0 then
264 # A simple set of sockets used by `SocketObserver`
266 private var native
= new NativeSocketSet
270 # Add `socket` to this set
271 fun add
(socket
: Socket) do native
.set
(socket
.socket
)
273 # Remove `socket` from this set
274 fun remove
(socket
: Socket) do native
.clear
(socket
.socket
)
276 # Does this set has `socket`?
277 fun has
(socket
: Socket): Bool do return native
.is_set
(socket
.socket
)
279 # Clear all sockets from this set
280 fun clear
do native
.zero
283 # Service class to manage calls to `select`
285 private var native
= new NativeSocketObserver
287 var read_set
: nullable SocketSet = null
289 var write_set
: nullable SocketSet = null
291 var except_set
: nullable SocketSet = null
293 init(read
: Bool, write
: Bool, except
: Bool)
295 if read
then read_set
= new SocketSet
296 if write
then write_set
= new SocketSet
297 if except
then except_set
= new SocketSet
300 fun select
(max
: Socket, seconds
: Int, microseconds
: Int): Bool
302 # FIXME this implementation (see the call to nullable attributes below) and
303 # `NativeSockectObserver::select` is not stable.
305 var timeval
= new NativeTimeval(seconds
, microseconds
)
306 return native
.select
(max
.socket
, read_set
.native
, write_set
.native
, except_set
.native
, timeval
) > 0