memcache/connection.c
changeset 38 9894df13b779
child 39 0e21a65074a6
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/memcache/connection.c	Tue Aug 26 01:30:53 2008 +0300
@@ -0,0 +1,86 @@
+
+#include <stdlib.h>
+#include <unistd.h>
+#include <assert.h>
+
+#include "connection.h"
+#include "../socket.h"
+#include "../common.h"
+
+static void _memcache_conn_ev_connect (evutil_socket_t fd, short what, void *arg);
+
+struct memcache_conn *memcache_conn_open (struct memcache_server *server) {
+    struct memcache_conn *conn = NULL;
+
+    if ((conn = calloc(1, sizeof(*conn))) == NULL)
+        ERROR("calloc");
+    
+    // remember the server
+    conn->server = server;
+    
+    // attempt connect
+    if (memcache_conn_connect(conn))
+        ERROR("failed to connect to server");
+    
+    // success
+    return conn;
+
+error:
+    free(conn);
+
+    return NULL;
+}
+
+int memcache_conn_connect (struct memcache_conn *conn) {
+    assert(conn->fd <= 0);
+    
+    // begin connect
+    if ((conn->fd = socket_connect_async(conn->server->endpoint, SOCK_STREAM)) == -1)
+        goto error;
+
+    // set up the connect event
+    event_set(&conn->ev, conn->fd, EV_WRITE, &_memcache_conn_ev_connect, conn);
+
+    // add it
+    if (event_add(&conn->ev, NULL))
+        PERROR("event_add");
+    
+    // success
+    return 0;
+
+error:
+    if (conn->fd > 0) {
+        if (close(conn->fd))
+            PWARNING("close %d", conn->fd);
+        
+        conn->fd = -1;
+    }
+   
+    return -1;
+}
+
+int memcache_conn_do_req (struct memcache_conn *conn, struct memcache_req *req) {
+    assert(conn->fd > 0);
+    assert(conn->req == NULL);
+
+    // store the req
+    conn->req = req;
+
+    // XXX: transmit it
+
+error:
+    return -1;
+}
+
+/*
+ * The connect() has finished
+ */
+static void _memcache_conn_ev_connect (evutil_socket_t fd, short what, void *arg) {
+    struct memcache_conn *conn = arg;
+
+   // XXX: check if the connect() failed
+
+    // notify the server
+    memcache_server_conn_ready(conn->server, conn);
+}
+