I'd like to know whether something like this has been done before:
I've recently started work on a networking library in C. The library maintains a set of sockets, each of which is associated with two FIFO byte streams, input and output.
A developer using the library is expected to register some callbacks, consisting of a recognizer function and a handler function. If new data ar开发者_开发技巧rives on a socket (i.e. the input stream), every recognizer is called. If one of the recognizers finds a matching portion of data, its associated handler is called, consuming the data and possibly queuing new data on the socket's output stream, scheduled to be transmitted later on.
Here's an example to make clear how the library is used:
// create client socket
client = nc_create(NC_CLIENT);
// register some callback functions that you'll have to supply yourself
nc_register_callback(client, &is_login, &on_login);
nc_register_callback(client, &is_password, &on_password);
// connect to server
nc_dial(client, "www.google.com", "23");
// start main loop (we might as well have more than one connection here)
nc_talk();
To me, this is the most obvious way to write a general purpose networking library in C. I did some research using Google, but I wasn't able to find something similar written in C. But it's hard to believe that I'm the first one that implements this approach.
Are there other data-driven general purpose C networking libraries like this out there? Would you use them?
Here's a few libraries that provides similar APIs, (at various levels, e.g. libevent provides a general callback driven API for socket/file descriptors)
libesmtp (example)
libevent
libcurl
The Sun/OncRPC APIs have a similar style, in that the library does the heavy lifting for you, dispatching requests to the proper callback handlers.
The Java netty and mina libraries works in a similar manner, although more object oriented.
精彩评论