]> git.saurik.com Git - wxWidgets.git/blobdiff - src/common/socket.cpp
documented the wxDCBrushChanger, wxDCPenChanger, wxDCTextColourChanger; introduced...
[wxWidgets.git] / src / common / socket.cpp
index d2ea4f5009c1b3838c6b8fdfab2fa589e58ef69a..2487fddcfb76b08aa7408bf97d807a8975cd4609 100644 (file)
@@ -42,6 +42,9 @@
 #include "wx/thread.h"
 #include "wx/evtloop.h"
 
+#include "wx/private/fd.h"
+#include "wx/private/socket.h"
+
 // DLL options compatibility check:
 #include "wx/build.h"
 WX_CHECK_BUILD_OPTIONS("wxNet")
@@ -83,6 +86,31 @@ public:
     DECLARE_NO_COPY_CLASS(wxSocketState)
 };
 
+// Conditionally make the socket non-blocking for the lifetime of this object.
+class wxSocketUnblocker
+{
+public:
+    wxSocketUnblocker(GSocket *socket, bool unblock = true)
+        : m_socket(socket),
+          m_unblock(unblock)
+    {
+        if ( m_unblock )
+            m_socket->SetNonBlocking(true);
+    }
+
+    ~wxSocketUnblocker()
+    {
+        if ( m_unblock )
+            m_socket->SetNonBlocking(false);
+    }
+
+private:
+    GSocket * const m_socket;
+    bool m_unblock;
+
+    DECLARE_NO_COPY_CLASS(wxSocketUnblocker)
+};
+
 // ============================================================================
 // GSocketManager
 // ============================================================================
@@ -127,6 +155,209 @@ void GSocketManager::Init()
     ms_manager = app->GetTraits()->GetSocketManager();
 }
 
+// ==========================================================================
+// GSocketBase
+// ==========================================================================
+
+/* static */
+GSocket *GSocketBase::Create(wxSocketBase& wxsocket)
+{
+    GSocket * const newsocket = new GSocket(wxsocket);
+    if ( !GSocketManager::Get()->Init_Socket(newsocket) )
+    {
+        delete newsocket;
+        return NULL;
+    }
+
+    return newsocket;
+}
+
+GSocketBase::GSocketBase(wxSocketBase& wxsocket)
+    : m_wxsocket(&wxsocket)
+{
+    m_fd              = INVALID_SOCKET;
+    m_detected        = 0;
+    m_local           = NULL;
+    m_peer            = NULL;
+    m_error           = GSOCK_NOERROR;
+    m_server          = false;
+    m_stream          = true;
+    m_non_blocking    = false;
+
+    SetTimeout(wxsocket.GetTimeout() * 1000);
+
+    m_establishing    = false;
+    m_reusable        = false;
+    m_broadcast       = false;
+    m_dobind          = true;
+    m_initialRecvBufferSize = -1;
+    m_initialSendBufferSize = -1;
+}
+
+GSocketBase::~GSocketBase()
+{
+    if (m_fd != INVALID_SOCKET)
+        Shutdown();
+
+    if (m_local)
+        GAddress_destroy(m_local);
+
+    if (m_peer)
+        GAddress_destroy(m_peer);
+
+    // cast is ok as all GSocketBase objects we have in our code are really
+    // GSockets
+    GSocketManager::Get()->Destroy_Socket(static_cast<GSocket *>(this));
+}
+
+void GSocketBase::Close()
+{
+    if ( m_fd != INVALID_SOCKET )
+    {
+        GSocketManager::Get()->Close_Socket(static_cast<GSocket *>(this));
+        m_fd = INVALID_SOCKET;
+    }
+}
+
+/* GSocket_Shutdown:
+ *  Disallow further read/write operations on this socket, close
+ *  the fd and disable all callbacks.
+ */
+void GSocketBase::Shutdown()
+{
+    if ( m_fd != INVALID_SOCKET )
+    {
+        shutdown(m_fd, 1 /* SD_SEND */);
+        Close();
+    }
+
+    m_detected = GSOCK_LOST_FLAG;
+}
+
+/* GSocket_SetTimeout:
+ *  Sets the timeout for blocking calls. Time is expressed in
+ *  milliseconds.
+ */
+void GSocketBase::SetTimeout(unsigned long millis)
+{
+    m_timeout.tv_sec  = (millis / 1000);
+    m_timeout.tv_usec = (millis % 1000) * 1000;
+}
+
+void GSocketBase::NotifyOnStateChange(GSocketEvent event)
+{
+    // GSocketEvent and wxSocketNotify enums have the same elements with the
+    // same values
+    m_wxsocket->OnRequest(static_cast<wxSocketNotify>(event));
+}
+
+/* Address handling */
+
+/* GSocket_SetLocal:
+ * GSocket_GetLocal:
+ * GSocket_SetPeer:
+ * GSocket_GetPeer:
+ *  Set or get the local or peer address for this socket. The 'set'
+ *  functions return GSOCK_NOERROR on success, an error code otherwise.
+ *  The 'get' functions return a pointer to a GAddress object on success,
+ *  or NULL otherwise, in which case they set the error code of the
+ *  corresponding GSocket.
+ *
+ *  Error codes:
+ *    GSOCK_INVSOCK - the socket is not valid.
+ *    GSOCK_INVADDR - the address is not valid.
+ */
+GSocketError GSocketBase::SetLocal(GAddress *address)
+{
+  /* the socket must be initialized, or it must be a server */
+  if (m_fd != INVALID_SOCKET && !m_server)
+  {
+    m_error = GSOCK_INVSOCK;
+    return GSOCK_INVSOCK;
+  }
+
+  /* check address */
+  if (address == NULL || address->m_family == GSOCK_NOFAMILY)
+  {
+    m_error = GSOCK_INVADDR;
+    return GSOCK_INVADDR;
+  }
+
+  if (m_local)
+    GAddress_destroy(m_local);
+
+  m_local = GAddress_copy(address);
+
+  return GSOCK_NOERROR;
+}
+
+GSocketError GSocketBase::SetPeer(GAddress *address)
+{
+  /* check address */
+  if (address == NULL || address->m_family == GSOCK_NOFAMILY)
+  {
+    m_error = GSOCK_INVADDR;
+    return GSOCK_INVADDR;
+  }
+
+  if (m_peer)
+    GAddress_destroy(m_peer);
+
+  m_peer = GAddress_copy(address);
+
+  return GSOCK_NOERROR;
+}
+
+GAddress *GSocketBase::GetLocal()
+{
+  GAddress *address;
+  wxSockAddr addr;
+  WX_SOCKLEN_T size = sizeof(addr);
+  GSocketError err;
+
+  /* try to get it from the m_local var first */
+  if (m_local)
+    return GAddress_copy(m_local);
+
+  /* else, if the socket is initialized, try getsockname */
+  if (m_fd == INVALID_SOCKET)
+  {
+    m_error = GSOCK_INVSOCK;
+    return NULL;
+  }
+
+  if (getsockname(m_fd, (sockaddr*)&addr, &size) == SOCKET_ERROR)
+  {
+    m_error = GSOCK_IOERR;
+    return NULL;
+  }
+
+  /* got a valid address from getsockname, create a GAddress object */
+  if ((address = GAddress_new()) == NULL)
+  {
+     m_error = GSOCK_MEMERR;
+     return NULL;
+  }
+
+  if ((err = _GAddress_translate_from(address, (sockaddr*)&addr, size)) != GSOCK_NOERROR)
+  {
+     GAddress_destroy(address);
+     m_error = err;
+     return NULL;
+  }
+
+  return address;
+}
+
+GAddress *GSocketBase::GetPeer()
+{
+  /* try to get it from the m_peer var */
+  if (m_peer)
+    return GAddress_copy(m_peer);
+
+  return NULL;
+}
+
 // ==========================================================================
 // wxSocketBase
 // ==========================================================================
@@ -219,8 +450,9 @@ wxSocketBase::wxSocketBase(wxSocketFlags flags, wxSocketType type)
 {
     Init();
 
-    m_flags = flags;
-    m_type  = type;
+    SetFlags(flags);
+
+    m_type = type;
 }
 
 wxSocketBase::~wxSocketBase()
@@ -288,18 +520,7 @@ bool wxSocketBase::Close()
     InterruptWait();
 
     if (m_socket)
-    {
-        // Disable callbacks
-        m_socket->UnsetCallback(
-            GSOCK_INPUT_FLAG |
-            GSOCK_OUTPUT_FLAG |
-            GSOCK_LOST_FLAG |
-            GSOCK_CONNECTION_FLAG
-        );
-
-        // Shutdown the connection
         m_socket->Shutdown();
-    }
 
     m_connected = false;
     m_establishing = false;
@@ -311,7 +532,7 @@ wxSocketBase& wxSocketBase::Read(void* buffer, wxUint32 nbytes)
     // Mask read events
     m_reading = true;
 
-    m_lcount = _Read(buffer, nbytes);
+    m_lcount = DoRead(buffer, nbytes);
 
     // If in wxSOCKET_WAITALL mode, all bytes should have been read.
     if (m_flags & wxSOCKET_WAITALL)
@@ -325,37 +546,31 @@ wxSocketBase& wxSocketBase::Read(void* buffer, wxUint32 nbytes)
     return *this;
 }
 
-wxUint32 wxSocketBase::_Read(void* buffer_, wxUint32 nbytes)
+wxUint32 wxSocketBase::DoRead(void* buffer_, wxUint32 nbytes)
 {
-    char *buffer = (char *)buffer_;
-
-    int total;
+    // We use pointer arithmetic here which doesn't work with void pointers.
+    char *buffer = static_cast<char *>(buffer_);
 
-    // Try the pushback buffer first
-    total = GetPushback(buffer, nbytes, false);
+    // Try the push back buffer first, even before checking whether the socket
+    // is valid to allow reading previously pushed back data from an already
+    // closed socket.
+    wxUint32 total = GetPushback(buffer, nbytes, false);
     nbytes -= total;
-    buffer  = (char *)buffer + total;
+    buffer += total;
 
-    // Return now in one of the following cases:
-    // - the socket is invalid,
-    // - we got all the data
-    if ( !m_socket ||
-            !nbytes )
+    // If it's indeed closed or if read everything, there is nothing more to do.
+    if ( !m_socket || !nbytes )
         return total;
 
-    // Possible combinations (they are checked in this order)
-    // wxSOCKET_NOWAIT
-    // wxSOCKET_WAITALL (with or without wxSOCKET_BLOCK)
-    // wxSOCKET_BLOCK
-    // wxSOCKET_NONE
-    //
-    int ret;
-    if (m_flags & wxSOCKET_NOWAIT)
-    {
-        m_socket->SetNonBlocking(1);
-        ret = m_socket->Read(buffer, nbytes);
-        m_socket->SetNonBlocking(0);
+    wxCHECK_MSG( buffer, 0, "NULL buffer" );
 
+
+    // wxSOCKET_NOWAIT overrides all the other flags and means that we are
+    // polling the socket and don't block at all.
+    if ( m_flags & wxSOCKET_NOWAIT )
+    {
+        wxSocketUnblocker unblock(m_socket);
+        int ret = m_socket->Read(buffer, nbytes);
         if ( ret < 0 )
             return 0;
 
@@ -365,11 +580,13 @@ wxUint32 wxSocketBase::_Read(void* buffer_, wxUint32 nbytes)
     {
         for ( ;; )
         {
-            // dispatch events unless disabled
+            // Wait until socket becomes ready for reading dispatching the GUI
+            // events in the meanwhile unless wxSOCKET_BLOCK was explicitly
+            // specified to disable this.
             if ( !(m_flags & wxSOCKET_BLOCK) && !WaitForRead() )
                 break;
 
-            ret = m_socket->Read(buffer, nbytes);
+            const int ret = m_socket->Read(buffer, nbytes);
             if ( ret == 0 )
             {
                 // for connection-oriented (e.g. TCP) sockets we can only read
@@ -388,18 +605,18 @@ wxUint32 wxSocketBase::_Read(void* buffer_, wxUint32 nbytes)
 
             total += ret;
 
-            // if wxSOCKET_WAITALL is not set, we can leave now as we did read
-            // something
+            // If wxSOCKET_WAITALL is not set, we can leave now as we did read
+            // something and we don't need to wait for all nbytes bytes to be
+            // read.
             if ( !(m_flags & wxSOCKET_WAITALL) )
                 break;
 
-            // otherwise check if read the maximal requested amount of data
+            // Otherwise continue reading until we do read everything.
             nbytes -= ret;
             if ( !nbytes )
                 break;
 
-            // we didn't, so continue reading
-            buffer  = (char *)buffer + ret;
+            buffer += ret;
         }
     }
 
@@ -425,7 +642,7 @@ wxSocketBase& wxSocketBase::ReadMsg(void* buffer, wxUint32 nbytes)
     old_flags = m_flags;
     SetFlags((m_flags & wxSOCKET_BLOCK) | wxSOCKET_WAITALL);
 
-    if (_Read(&msg, sizeof(msg)) != sizeof(msg))
+    if (DoRead(&msg, sizeof(msg)) != sizeof(msg))
         goto exit;
 
     sig = (wxUint32)msg.sig[0];
@@ -455,7 +672,7 @@ wxSocketBase& wxSocketBase::ReadMsg(void* buffer, wxUint32 nbytes)
     // Don't attempt to read if the msg was zero bytes long.
     if (len)
     {
-        total = _Read(buffer, len);
+        total = DoRead(buffer, len);
 
         if (total != len)
             goto exit;
@@ -470,7 +687,7 @@ wxSocketBase& wxSocketBase::ReadMsg(void* buffer, wxUint32 nbytes)
         do
         {
             discard_len = ((len2 > MAX_DISCARD_SIZE)? MAX_DISCARD_SIZE : len2);
-            discard_len = _Read(discard_buffer, (wxUint32)discard_len);
+            discard_len = DoRead(discard_buffer, (wxUint32)discard_len);
             len2 -= (wxUint32)discard_len;
         }
         while ((discard_len > 0) && len2);
@@ -480,7 +697,7 @@ wxSocketBase& wxSocketBase::ReadMsg(void* buffer, wxUint32 nbytes)
         if (len2 != 0)
             goto exit;
     }
-    if (_Read(&msg, sizeof(msg)) != sizeof(msg))
+    if (DoRead(&msg, sizeof(msg)) != sizeof(msg))
         goto exit;
 
     sig = (wxUint32)msg.sig[0];
@@ -511,7 +728,7 @@ wxSocketBase& wxSocketBase::Peek(void* buffer, wxUint32 nbytes)
     // Mask read events
     m_reading = true;
 
-    m_lcount = _Read(buffer, nbytes);
+    m_lcount = DoRead(buffer, nbytes);
     Pushback(buffer, m_lcount);
 
     // If in wxSOCKET_WAITALL mode, all bytes should have been read.
@@ -531,7 +748,7 @@ wxSocketBase& wxSocketBase::Write(const void *buffer, wxUint32 nbytes)
     // Mask write events
     m_writing = true;
 
-    m_lcount = _Write(buffer, nbytes);
+    m_lcount = DoWrite(buffer, nbytes);
 
     // If in wxSOCKET_WAITALL mode, all bytes should have been written.
     if (m_flags & wxSOCKET_WAITALL)
@@ -545,31 +762,25 @@ wxSocketBase& wxSocketBase::Write(const void *buffer, wxUint32 nbytes)
     return *this;
 }
 
-wxUint32 wxSocketBase::_Write(const void *buffer_, wxUint32 nbytes)
+// This function is a mirror image of DoRead() except that it doesn't use the
+// push back buffer, please see comments there
+wxUint32 wxSocketBase::DoWrite(const void *buffer_, wxUint32 nbytes)
 {
-    const char *buffer = (const char *)buffer_;
-
-    wxUint32 total = 0;
+    const char *buffer = static_cast<const char *>(buffer_);
 
-    // If the socket is invalid or parameters are ill, return immediately
-    if (!m_socket || !buffer || !nbytes)
+    // Return if there is nothing to read or the socket is (already?) closed.
+    if ( !m_socket || !nbytes )
         return 0;
 
-    // Possible combinations (they are checked in this order)
-    // wxSOCKET_NOWAIT
-    // wxSOCKET_WAITALL (with or without wxSOCKET_BLOCK)
-    // wxSOCKET_BLOCK
-    // wxSOCKET_NONE
-    //
-    int ret;
-    if (m_flags & wxSOCKET_NOWAIT)
-    {
-        m_socket->SetNonBlocking(1);
-        ret = m_socket->Write(buffer, nbytes);
-        m_socket->SetNonBlocking(0);
+    wxCHECK_MSG( buffer, 0, "NULL buffer" );
 
-        if (ret > 0)
-            total = ret;
+    wxUint32 total = 0;
+    if ( m_flags & wxSOCKET_NOWAIT )
+    {
+        wxSocketUnblocker unblock(m_socket);
+        const int ret = m_socket->Write(buffer, nbytes);
+        if ( ret > 0 )
+            total += ret;
     }
     else // blocking socket
     {
@@ -578,9 +789,7 @@ wxUint32 wxSocketBase::_Write(const void *buffer_, wxUint32 nbytes)
             if ( !(m_flags & wxSOCKET_BLOCK) && !WaitForWrite() )
                 break;
 
-            ret = m_socket->Write(buffer, nbytes);
-
-            // see comments for similar logic for ret handling in _Read()
+            const int ret = m_socket->Write(buffer, nbytes);
             if ( ret == 0 )
             {
                 m_closed = true;
@@ -588,9 +797,7 @@ wxUint32 wxSocketBase::_Write(const void *buffer_, wxUint32 nbytes)
             }
 
             if ( ret < 0 )
-            {
                 return 0;
-            }
 
             total += ret;
             if ( !(m_flags & wxSOCKET_WAITALL) )
@@ -600,7 +807,7 @@ wxUint32 wxSocketBase::_Write(const void *buffer_, wxUint32 nbytes)
             if ( !nbytes )
                 break;
 
-            buffer = (const char *)buffer + ret;
+            buffer += ret;
         }
     }
 
@@ -634,10 +841,10 @@ wxSocketBase& wxSocketBase::WriteMsg(const void *buffer, wxUint32 nbytes)
     msg.len[2] = (unsigned char) ((nbytes >> 16) & 0xff);
     msg.len[3] = (unsigned char) ((nbytes >> 24) & 0xff);
 
-    if (_Write(&msg, sizeof(msg)) < sizeof(msg))
+    if (DoWrite(&msg, sizeof(msg)) < sizeof(msg))
         goto exit;
 
-    total = _Write(buffer, nbytes);
+    total = DoWrite(buffer, nbytes);
 
     if (total < nbytes)
         goto exit;
@@ -651,7 +858,7 @@ wxSocketBase& wxSocketBase::WriteMsg(const void *buffer, wxUint32 nbytes)
     msg.len[2] =
     msg.len[3] = (char) 0;
 
-    if ((_Write(&msg, sizeof(msg))) < sizeof(msg))
+    if ((DoWrite(&msg, sizeof(msg))) < sizeof(msg))
         goto exit;
 
     // everything was OK
@@ -689,7 +896,7 @@ wxSocketBase& wxSocketBase::Discard()
 
     do
     {
-        ret = _Read(buffer, MAX_DISCARD_SIZE);
+        ret = DoRead(buffer, MAX_DISCARD_SIZE);
         total += ret;
     }
     while (ret == MAX_DISCARD_SIZE);
@@ -708,6 +915,112 @@ wxSocketBase& wxSocketBase::Discard()
 // Wait functions
 // --------------------------------------------------------------------------
 
+/* GSocket_Select:
+ *  Polls the socket to determine its status. This function will
+ *  check for the events specified in the 'flags' parameter, and
+ *  it will return a mask indicating which operations can be
+ *  performed. This function won't block, regardless of the
+ *  mode (blocking | nonblocking) of the socket.
+ */
+GSocketEventFlags GSocketBase::Select(GSocketEventFlags flags)
+{
+  assert(this);
+
+  GSocketEventFlags result = 0;
+  fd_set readfds;
+  fd_set writefds;
+  fd_set exceptfds;
+  struct timeval tv;
+
+  if (m_fd == -1)
+    return (GSOCK_LOST_FLAG & flags);
+
+  /* Do not use a static struct, Linux can garble it */
+  tv.tv_sec = 0;
+  tv.tv_usec = 0;
+
+  wxFD_ZERO(&readfds);
+  wxFD_ZERO(&writefds);
+  wxFD_ZERO(&exceptfds);
+  wxFD_SET(m_fd, &readfds);
+  if (flags & GSOCK_OUTPUT_FLAG || flags & GSOCK_CONNECTION_FLAG)
+    wxFD_SET(m_fd, &writefds);
+  wxFD_SET(m_fd, &exceptfds);
+
+  /* Check 'sticky' CONNECTION flag first */
+  result |= GSOCK_CONNECTION_FLAG & m_detected;
+
+  /* If we have already detected a LOST event, then don't try
+   * to do any further processing.
+   */
+  if ((m_detected & GSOCK_LOST_FLAG) != 0)
+  {
+    m_establishing = false;
+    return (GSOCK_LOST_FLAG & flags);
+  }
+
+  /* Try select now */
+  if (select(m_fd + 1, &readfds, &writefds, &exceptfds, &tv) < 0)
+  {
+    /* What to do here? */
+    return (result & flags);
+  }
+
+  /* Check for exceptions and errors */
+  if (wxFD_ISSET(m_fd, &exceptfds))
+  {
+    m_establishing = false;
+    m_detected = GSOCK_LOST_FLAG;
+
+    /* LOST event: Abort any further processing */
+    return (GSOCK_LOST_FLAG & flags);
+  }
+
+  /* Check for readability */
+  if (wxFD_ISSET(m_fd, &readfds))
+  {
+    result |= GSOCK_INPUT_FLAG;
+
+    if (m_server && m_stream)
+    {
+      /* This is a TCP server socket that detected a connection.
+         While the INPUT_FLAG is also set, it doesn't matter on
+         this kind of  sockets, as we can only Accept() from them. */
+      m_detected |= GSOCK_CONNECTION_FLAG;
+    }
+  }
+
+  /* Check for writability */
+  if (wxFD_ISSET(m_fd, &writefds))
+  {
+    if (m_establishing && !m_server)
+    {
+      int error;
+      SOCKOPTLEN_T len = sizeof(error);
+      m_establishing = false;
+      getsockopt(m_fd, SOL_SOCKET, SO_ERROR, (char*)&error, &len);
+
+      if (error)
+      {
+        m_detected = GSOCK_LOST_FLAG;
+
+        /* LOST event: Abort any further processing */
+        return (GSOCK_LOST_FLAG & flags);
+      }
+      else
+      {
+        m_detected |= GSOCK_CONNECTION_FLAG;
+      }
+    }
+    else
+    {
+      result |= GSOCK_OUTPUT_FLAG;
+    }
+  }
+
+  return (result | m_detected) & flags;
+}
+
 // All Wait functions poll the socket using GSocket_Select() to
 // check for the specified combination of conditions, until one
 // of these conditions become true, an error occurs, or the
@@ -737,11 +1050,6 @@ wxSocketBase::DoWait(long seconds, long milliseconds, wxSocketEventFlags flags)
     if ( wxIsMainThread() )
     {
         eventLoop = wxEventLoop::GetActive();
-
-#ifdef __WXMSW__
-        wxASSERT_MSG( eventLoop,
-                      "Sockets won't work without a running event loop" );
-#endif // __WXMSW__
     }
     else // in worker thread
     {
@@ -796,10 +1104,9 @@ wxSocketBase::DoWait(long seconds, long milliseconds, wxSocketEventFlags flags)
 
         if ( eventLoop )
         {
-            // Dispatch the events when we run in the main thread and have an
-            // active event loop: without this sockets don't work at all under
-            // MSW as socket flags are only updated when socket messages are
-            // processed.
+            // This function is only called if wxSOCKET_BLOCK flag was not used
+            // and so we should dispatch the events if there is an event loop
+            // capable of doing it.
             if ( eventLoop->Pending() )
                 eventLoop->Dispatch();
         }
@@ -944,6 +1251,13 @@ void wxSocketBase::SetTimeout(long seconds)
 
 void wxSocketBase::SetFlags(wxSocketFlags flags)
 {
+    // Do some sanity checking on the flags used: not all values can be used
+    // together.
+    wxASSERT_MSG( !(flags & wxSOCKET_NOWAIT) ||
+                  !(flags & (wxSOCKET_WAITALL | wxSOCKET_BLOCK)),
+                  "Using wxSOCKET_WAITALL or wxSOCKET_BLOCK with "
+                  "wxSOCKET_NOWAIT doesn't make sense" );
+
     m_flags = flags;
 }
 
@@ -952,34 +1266,6 @@ void wxSocketBase::SetFlags(wxSocketFlags flags)
 // Event handling
 // --------------------------------------------------------------------------
 
-// A note on how events are processed, which is probably the most
-// difficult thing to get working right while keeping the same API
-// and functionality for all platforms.
-//
-// When GSocket detects an event, it calls wx_socket_callback, which in
-// turn just calls wxSocketBase::OnRequest in the corresponding wxSocket
-// object. OnRequest does some housekeeping, and if the event is to be
-// propagated to the user, it creates a new wxSocketEvent object and
-// posts it. The event is not processed immediately, but delayed with
-// AddPendingEvent instead. This is necessary in order to decouple the
-// event processing from wx_socket_callback; otherwise, subsequent IO
-// calls made from the user event handler would fail, as gtk callbacks
-// are not reentrant.
-//
-// Note that, unlike events, user callbacks (now deprecated) are _not_
-// decoupled from wx_socket_callback and thus they suffer from a variety
-// of problems. Avoid them where possible and use events instead.
-
-extern "C"
-void LINKAGEMODE wx_socket_callback(GSocket * WXUNUSED(socket),
-                                    GSocketEvent notification,
-                                    char *cdata)
-{
-    wxSocketBase *sckobj = (wxSocketBase *)cdata;
-
-    sckobj->OnRequest((wxSocketNotify) notification);
-}
-
 void wxSocketBase::OnRequest(wxSocketNotify notification)
 {
     switch(notification)
@@ -1084,6 +1370,8 @@ void wxSocketBase::Pushback(const void *buffer, wxUint32 size)
 
 wxUint32 wxSocketBase::GetPushback(void *buffer, wxUint32 size, bool peek)
 {
+    wxCHECK_MSG( buffer, 0, "NULL buffer" );
+
     if (!m_unrd_size)
         return 0;
 
@@ -1122,7 +1410,7 @@ wxSocketServer::wxSocketServer(const wxSockAddress& addr_man,
 {
     wxLogTrace( wxTRACE_Socket, _T("Opening wxSocketServer") );
 
-    m_socket = GSocket_new();
+    m_socket = GSocket::Create(*this);
 
     if (!m_socket)
     {
@@ -1153,11 +1441,6 @@ wxSocketServer::wxSocketServer(const wxSockAddress& addr_man,
         return;
     }
 
-    m_socket->SetTimeout(m_timeout * 1000);
-    m_socket->SetCallback(GSOCK_INPUT_FLAG | GSOCK_OUTPUT_FLAG |
-                                  GSOCK_LOST_FLAG | GSOCK_CONNECTION_FLAG,
-                                  wx_socket_callback, (char *)this);
-
     wxLogTrace( wxTRACE_Socket, _T("wxSocketServer on fd %d"), m_socket->m_fd );
 }
 
@@ -1167,35 +1450,21 @@ wxSocketServer::wxSocketServer(const wxSockAddress& addr_man,
 
 bool wxSocketServer::AcceptWith(wxSocketBase& sock, bool wait)
 {
-    GSocket *child_socket;
-
     if (!m_socket)
         return false;
 
     // If wait == false, then the call should be nonblocking.
     // When we are finished, we put the socket to blocking mode
     // again.
+    wxSocketUnblocker unblock(m_socket, !wait);
+    sock.m_socket = m_socket->WaitConnection(sock);
 
-    if (!wait)
-        m_socket->SetNonBlocking(1);
-
-    child_socket = m_socket->WaitConnection();
-
-    if (!wait)
-        m_socket->SetNonBlocking(0);
-
-    if (!child_socket)
+    if ( !sock.m_socket )
         return false;
 
     sock.m_type = wxSOCKET_BASE;
-    sock.m_socket = child_socket;
     sock.m_connected = true;
 
-    sock.m_socket->SetTimeout(sock.m_timeout * 1000);
-    sock.m_socket->SetCallback(GSOCK_INPUT_FLAG | GSOCK_OUTPUT_FLAG |
-            GSOCK_LOST_FLAG | GSOCK_CONNECTION_FLAG,
-            wx_socket_callback, (char *)&sock);
-
     return true;
 }
 
@@ -1286,8 +1555,6 @@ bool wxSocketClient::DoConnect(const wxSockAddress& addr_man,
                                const wxSockAddress* local,
                                bool wait)
 {
-    GSocketError err;
-
     if (m_socket)
     {
         // Shutdown and destroy the socket
@@ -1295,28 +1562,16 @@ bool wxSocketClient::DoConnect(const wxSockAddress& addr_man,
         delete m_socket;
     }
 
-    m_socket = GSocket_new();
+    m_socket = GSocket::Create(*this);
     m_connected = false;
     m_establishing = false;
 
     if (!m_socket)
         return false;
 
-    m_socket->SetTimeout(m_timeout * 1000);
-    m_socket->SetCallback(
-        GSOCK_INPUT_FLAG |
-        GSOCK_OUTPUT_FLAG |
-        GSOCK_LOST_FLAG |
-        GSOCK_CONNECTION_FLAG,
-        wx_socket_callback,
-        (char *)this
-    );
-
     // If wait == false, then the call should be nonblocking. When we are
     // finished, we put the socket to blocking mode again.
-
-    if (!wait)
-        m_socket->SetNonBlocking(1);
+    wxSocketUnblocker unblock(m_socket, !wait);
 
     // Reuse makes sense for clients too, if we are trying to rebind to the same port
     if (GetFlags() & wxSOCKET_REUSEADDR)
@@ -1352,14 +1607,11 @@ bool wxSocketClient::DoConnect(const wxSockAddress& addr_man,
 #endif
 
     m_socket->SetPeer(addr_man.GetAddress());
-    err = m_socket->Connect(GSOCK_STREAMED);
+    const GSocketError err = m_socket->Connect(GSOCK_STREAMED);
 
     //this will register for callbacks - must be called after m_socket->m_fd was initialized
     m_socket->Notify(m_notify);
 
-    if (!wait)
-        m_socket->SetNonBlocking(0);
-
     if (err != GSOCK_NOERROR)
     {
         if (err == GSOCK_WOULDBLOCK)
@@ -1415,13 +1667,11 @@ wxDatagramSocket::wxDatagramSocket( const wxSockAddress& addr,
                 : wxSocketBase( flags, wxSOCKET_DATAGRAM )
 {
     // Create the socket
-    m_socket = GSocket_new();
+    m_socket = GSocket::Create(*this);
 
     if (!m_socket)
-    {
-        wxFAIL_MSG( _T("datagram socket not new'd") );
         return;
-    }
+
     m_socket->Notify(m_notify);
     // Setup the socket as non connection oriented
     m_socket->SetLocal(addr.GetAddress());
@@ -1447,10 +1697,6 @@ wxDatagramSocket::wxDatagramSocket( const wxSockAddress& addr,
     // Initialize all stuff
     m_connected = false;
     m_establishing = false;
-    m_socket->SetTimeout( m_timeout );
-    m_socket->SetCallback( GSOCK_INPUT_FLAG | GSOCK_OUTPUT_FLAG |
-                           GSOCK_LOST_FLAG | GSOCK_CONNECTION_FLAG,
-                           wx_socket_callback, (char*)this );
 }
 
 wxDatagramSocket& wxDatagramSocket::RecvFrom( wxSockAddress& addr,