sysapps / tcp-udp-sockets

Raw sockets API
85 stars 25 forks source link

Creating the socket and connecting should be seperate concepts #52

Open nickdesaulniers opened 11 years ago

nickdesaulniers commented 11 years ago

This would minimize object creation when trying to implement socket pooling. For example:

let TCPSocketPool = [];

// populate socket pool
for (let i = 11; --i;) {
  TCPSocketPool.push(new TCPSocket());
}

// when a socket it needed, instead of constructing a new object, just call:
let socket = TCPSocketPool.shift();

// use socket
socket.connect("127.0.0.1", "9001");
// ...

// send back to pool when done
socket.onclose = function () {
  TCPSocketPool.push(this);
};

This separation of creating the socket and connecting would be more familiar to developers with Unix socket programming backgrounds as well.

ClaesNilsson commented 11 years ago

The reason why I chose the design that combines the TCP socket creation and peer connect in the constructor is that this is the design used by Web Sockets and that it is a simple design.

I can understand use cases in which an application reuses an existing connected socket to a certain peer for more data to send to that peer as setting up a new peer connection requires some overhead. However, I am not sure that I understand the benefit of using a pool of empty, unconnected TCP socket objects. Could you elaborate on that?

Changing the API to use a separate method for connect is easy but I need to understand the benefits of doing that, especially as that would make the design different from Web Sockets.

nickdesaulniers commented 11 years ago

Allowing for a pooling abstraction allows developers to more properly anticipate GC pauses, in general. Specifically, I cannot think of any case where a pool of TCP sockets would be combined with high performance JavaScript that relies on object pools to control GC pauses, but that could just be a lack of imagination on my part.