Permalink
Browse files

tcp: close()

  • Loading branch information...
1 parent 29ca6ac commit e6da8f44ec87bbe268f02236704597c61de29536 @indutny committed Nov 4, 2012
Showing with 41 additions and 1 deletion.
  1. +5 −1 lib/tcp.can
  2. +32 −0 src/bindings/tcp.cc
  3. +4 −0 src/bindings/tcp.h
View
@@ -15,13 +15,17 @@ Server.init = (self, listener) {
Server.listen = (self, port, host) {
tcp.bind(self._handle, port, host || "0.0.0.0")
- tcp.listen(self._handle, 10, (socket) {
+ tcp.listen(self._handle, 511, (socket) {
self._listener(socket)
})
return self
}
+Server.close = (self, cb) {
+ tcp.close(self._handle, cb || () {})
+}
+
exports.createServer = (listener) {
s = clone Server
return s:init(listener)
View
@@ -86,10 +86,42 @@ Value* TCP::Listen(uint32_t argc, Value** argv) {
}
+void TCP::OnClose(uv_handle_t* handle) {
+ TCP* s = reinterpret_cast<TCP*>(handle->data);
+
+ if (!s->close_cb_.IsEmpty()) {
+ s->close_cb_->Call(0, NULL);
+ s->close_cb_.Unwrap();
+ s->Unref();
+ }
+}
+
+
+Value* TCP::Close(uint32_t argc, Value** argv) {
+ if (argc < 2 || !TCP::HasInstance(argv[0]) || !argv[1]->Is<Function>()) {
+ return Nil::New();
+ }
+
+ Function* cb = argv[1]->As<Function>();
+ TCP* t = CWrapper::Unwrap<TCP>(argv[0]);
+
+ // Already closing/closed - just return
+ if (uv_is_closing(reinterpret_cast<uv_handle_t*>(&t->handle_))) {
+ return Number::NewIntegral(-1);
+ }
+
+ t->close_cb_.Wrap(cb);
+ uv_close(reinterpret_cast<uv_handle_t*>(&t->handle_), OnClose);
+
+ return Nil::New();
+}
+
+
void TCP::Init(Object* target) {
target->Set("new", Function::New(TCP::New));
target->Set("bind", Function::New(TCP::Bind));
target->Set("listen", Function::New(TCP::Listen));
+ target->Set("close", Function::New(TCP::Close));
}
} // namespace can
View
@@ -11,6 +11,7 @@ namespace can {
class TCP : public candor::CWrapper {
public:
TCP() : candor::CWrapper(&magic) {
+ Ref();
}
static void Init(candor::Object* target);
@@ -22,14 +23,17 @@ class TCP : public candor::CWrapper {
protected:
static void OnConnection(uv_stream_t* server, int status);
+ static void OnClose(uv_handle_t* server);
static candor::Value* New(uint32_t argc, candor::Value** argv);
static candor::Value* Bind(uint32_t argc, candor::Value** argv);
static candor::Value* Listen(uint32_t argc, candor::Value** argv);
+ static candor::Value* Close(uint32_t argc, candor::Value** argv);
uv_tcp_t handle_;
candor::Handle<candor::Function> connection_cb_;
+ candor::Handle<candor::Function> close_cb_;
};
} // namespace can

0 comments on commit e6da8f4

Please sign in to comment.