⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 gsocket.cpp

📁 Wxpython Implemented on Windows CE, Source code
💻 CPP
📖 第 1 页 / 共 3 页
字号:
    return NULL;
  }

  /* Create a GSocket object for the new connection */
  connection = GSocket_new();

  if (!connection)
  {
    m_error = GSOCK_MEMERR;
    return NULL;
  }

  /* Wait for a connection (with timeout) */
  if (Input_Timeout() == GSOCK_TIMEDOUT)
  {
    delete connection;
    /* m_error set by _GSocket_Input_Timeout */
    return NULL;
  }

// TODO
#if 0
  connection->m_endpoint = accept(m_endpoint, &from, (WX_SOCKLEN_T *) &fromlen);
#endif

  if (connection->m_endpoint == kOTInvalidEndpointRef )
  {
    if (errno == EWOULDBLOCK)
      m_error = GSOCK_WOULDBLOCK;
    else
      m_error = GSOCK_IOERR;

    delete connection;
    return NULL;
  }

  /* Initialize all fields */
  connection->m_server   = false;
  connection->m_stream   = true;
  connection->m_oriented = true;

  /* Setup the peer address field */
  connection->m_peer = GAddress_new();
  if (!connection->m_peer)
  {
    delete connection;
    m_error = GSOCK_MEMERR;
    return NULL;
  }
 // TODO
 #if 0
  err = _GAddress_translate_from(connection->m_peer, &from, fromlen);
  if (err != GSOCK_NOERROR)
  {
    GAddress_destroy(connection->m_peer);
    GSocket_destroy(connection);
    m_error = err;
    return NULL;
  }

  ioctl(connection->m_endpoint, FIONBIO, &arg);
#endif
  connection->Enable_Events();

  return connection;
}

/* Datagram sockets */

/* GSocket_SetNonOriented:
 *  Sets up this socket as a non-connection oriented (datagram) socket.
 *  Before using this function, the local address must have been set
 *  with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
 *  on success, or one of the following otherwise.
 *
 *  Error codes:
 *    GSOCK_INVSOCK - the socket is in use.
 *    GSOCK_INVADDR - the local address has not been set.
 *    GSOCK_IOERR   - low-level error.
 */
GSocketError GSocket::SetNonOriented()
{
  assert(this);

  if (m_endpoint != kOTInvalidEndpointRef )
  {
    m_error = GSOCK_INVSOCK;
    return GSOCK_INVSOCK;
  }

  if (!m_local)
  {
    m_error = GSOCK_INVADDR;
    return GSOCK_INVADDR;
  }

  /* Initialize all fields */
  m_stream   = false;
  m_server   = false;
  m_oriented = false;

  /* Create the socket */

// TODO
#if 0
  m_endpoint = socket(m_local->m_realfamily, SOCK_DGRAM, 0);
  socket_set_ref( m_endpoint , (unsigned long) &gMacNetEvents ,  (unsigned long) this ) ;
#endif
  if (m_endpoint == kOTInvalidEndpointRef )
  {
    m_error = GSOCK_IOERR;
    return GSOCK_IOERR;
  }

// TODO
#if 0
  ioctl(m_endpoint, FIONBIO, &arg);
#endif
  Enable_Events();

  /* Bind to the local address,
   * and retrieve the actual address bound.
   */
// TODO
#if 0
  if ((bind(m_endpoint, m_local->m_addr, m_local->m_len) != 0) ||
      (getsockname(m_endpoint,
                   m_local->m_addr,
                   (WX_SOCKLEN_T *) &m_local->m_len) != 0))
  {
    close(m_endpoint);
    m_endpoint    = -1;
    m_error = GSOCK_IOERR;
    return GSOCK_IOERR;
  }
#endif
  return GSOCK_NOERROR;
}

/* Client specific parts */

/* GSocket_Connect:
 *  For stream (connection oriented) sockets, GSocket_Connect() tries
 *  to establish a client connection to a server using the peer address
 *  as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
 *  connection has been successfully established, or one of the error
 *  codes listed below. Note that for nonblocking sockets, a return
 *  value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
 *  request can be completed later; you should use GSocket_Select()
 *  to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
 *  corresponding asynchronous events.
 *
 *  For datagram (non connection oriented) sockets, GSocket_Connect()
 *  just sets the peer address established with GSocket_SetPeer() as
 *  default destination.
 *
 *  Error codes:
 *    GSOCK_INVSOCK    - the socket is in use or not valid.
 *    GSOCK_INVADDR    - the peer address has not been established.
 *    GSOCK_TIMEDOUT   - timeout, the connection failed.
 *    GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
 *    GSOCK_MEMERR     - couldn't allocate memory.
 *    GSOCK_IOERR      - low-level error.
 */
GSocketError GSocket::Connect(GSocketStream stream)
{
  InetAddress addr ;
  TEndpointInfo   info;
   OSStatus       err = kOTNoError;
  TCall peer ;

  assert(this);

  /* Enable CONNECTION events (needed for nonblocking connections) */
  m_detected &= ~GSOCK_CONNECTION_FLAG;

  if (m_endpoint != kOTInvalidEndpointRef )
  {
    m_error = GSOCK_INVSOCK;
    return GSOCK_INVSOCK;
  }

  if (!m_peer)
  {
    m_error = GSOCK_INVADDR;
    return GSOCK_INVADDR;
  }

  /* Streamed or dgram socket? */
  m_stream   = (stream == GSOCK_STREAMED);
  m_oriented = true;
  m_server   = false;

  /* Create the socket */
#if TARGET_CARBON
  m_endpoint =
      OTOpenEndpointInContext( OTCreateConfiguration( kTCPName) , 0 , &info , &err , NULL ) ;
#else
  m_endpoint =
      OTOpenEndpoint( OTCreateConfiguration( kTCPName) , 0 , &info , &err ) ;
#endif
  if ( m_endpoint == kOTInvalidEndpointRef || err != kOTNoError )
  {
    m_endpoint = kOTInvalidEndpointRef ;
    m_error = GSOCK_IOERR;
    return GSOCK_IOERR;
  }
  err = OTBind( m_endpoint , nil , nil ) ;
  if ( err != kOTNoError )
  {
    return GSOCK_IOERR;
  }
  SetDefaultEndpointModes( m_endpoint , this ) ;
// TODO
#if 0
  ioctl(m_endpoint, FIONBIO, &arg);
#endif
  Enable_Events();

  _GAddress_translate_to( m_peer , &addr ) ;
  memset( &peer , 0 , sizeof( TCall ) ) ;
  peer.addr.len = sizeof( InetAddress ) ;
  peer.addr.buf = (unsigned char*) &addr ;
  err = OTConnect( m_endpoint , &peer , nil ) ;
  if ( err != noErr )
  {
    /* If connect failed with EINPROGRESS and the GSocket object
     * is in blocking mode, we select() for the specified timeout
     * checking for writability to see if the connection request
     * completes.
     */

    if ((err == kOTNoDataErr ) && (!m_non_blocking))
    {
      if (Output_Timeout() == GSOCK_TIMEDOUT)
      {
        OTSndOrderlyDisconnect( m_endpoint ) ;
        m_endpoint = kOTInvalidEndpointRef ;
        /* m_error is set in _GSocket_Output_Timeout */
        return GSOCK_TIMEDOUT;
      }
      else
      {
/*
        int error;
        WX_SOCKLEN_T len = sizeof(error);

        getsockopt(m_endpoint, SOL_SOCKET, SO_ERROR, (void*) &error, &len);

        if (!error)
*/
          return GSOCK_NOERROR;
      }
    }

    /* If connect failed with EINPROGRESS and the GSocket object
     * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
     * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
     * this way if the connection completes, a GSOCK_CONNECTION
     * event will be generated, if enabled.
     */
    if ((err == kOTNoDataErr) && (m_non_blocking))
    {
      m_error = GSOCK_WOULDBLOCK;
      return GSOCK_WOULDBLOCK;
    }

    /* If connect failed with an error other than EINPROGRESS,
     * then the call to GSocket_Connect has failed.
     */
    OTSndOrderlyDisconnect( m_endpoint ) ;

    m_endpoint = kOTInvalidEndpointRef ;
    m_error = GSOCK_IOERR;
    return GSOCK_IOERR;
  }
//  OTInetEventHandler(this, T_CONNECT , kOTNoError , NULL ) ;
  return GSOCK_NOERROR;
}

/* Generic IO */

/* Like recv(), send(), ... */
int GSocket::Read(char *buffer, int size)
{
  int ret = 0 ;

  assert(this);

  /* Reenable INPUT events */
  m_detected &= ~GSOCK_INPUT_FLAG;

  if (m_endpoint == kOTInvalidEndpointRef || m_server)
  {
    m_error = GSOCK_INVSOCK;
    return -1;
  }

  /* If the socket is blocking, wait for data (with a timeout) */
  if (Input_Timeout() == GSOCK_TIMEDOUT)
    return -1;

  /* Read the data */
  if (m_stream)
    ret = Recv_Stream(buffer, size);
  else
    ret = Recv_Dgram(buffer, size);

  if (ret == -1)
  {
    if (errno == EWOULDBLOCK)
      m_error = GSOCK_WOULDBLOCK;
    else
      m_error = GSOCK_IOERR;
  }

  return ret;
}

int GSocket::Write(const char *buffer, int size)
{
  int ret;

  assert(this);

  if (m_endpoint == kOTInvalidEndpointRef || m_server)
  {
    m_error = GSOCK_INVSOCK;
    return -1;
  }

  /* If the socket is blocking, wait for writability (with a timeout) */
  if (Output_Timeout() == GSOCK_TIMEDOUT)
    return -1;

  /* Write the data */
  if (m_stream)
    ret = Send_Stream(buffer, size);
  else
    ret = Send_Dgram(buffer, size);

  if (ret == -1)
  {
    if (errno == EWOULDBLOCK)
      m_error = GSOCK_WOULDBLOCK;
    else
      m_error = GSOCK_IOERR;

    /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
     * in MSW). Once the first OUTPUT event is received, users can assume
     * that the socket is writable until a read operation fails. Only then
     * will further OUTPUT events be posted.
     */
    m_detected &= ~GSOCK_OUTPUT_FLAG;
    return -1;
  }

  return ret;
}

/* 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 GSocket::Select(GSocketEventFlags flags)
{
  assert(this);
  wxMacProcessNotifierEvents() ;
  /*
  state = OTGetEndpointState(m_endpoint);

  if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( m_detected & GSOCK_INPUT_FLAG ) )
  {
    size_t sz = 0 ;
    OTCountDataBytes( m_endpoint , &sz ) ;
    if ( state == T_INCON || sz > 0 )
    {
      m_detected |= GSOCK_INPUT_FLAG ;
      (m_cbacks[GSOCK_INPUT])(this, GSOCK_INPUT, m_data[GSOCK_INPUT]);
    }
  }
  if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( m_detected & GSOCK_OUTPUT_FLAG ) )
  {
    if ( state == T_DATAXFER || state == T_INREL )
    {
      m_detected |=GSOCK_OUTPUT_FLAG ;
      (m_cbacks[GSOCK_OUTPUT])(this, GSOCK_OUTPUT, m_data[GSOCK_OUTPUT]);
    }
  }
  */
  return ( flags & m_detected ) ;
}

/* Flags */

/* GSocket_SetNonBlocking:
 *  Sets the socket to non-blocking mode. All IO calls will return
 *  immediately.
 */
void GSocket::SetNonBlocking(bool non_block)
{
  assert(this);

  m_non_blocking = non_block;
}

/* GSocket_SetTimeout:
 *  Sets the timeout for blocking calls. Time is expressed in
 *  milliseconds.
 */
void GSocket::SetTimeout(unsigned long millisec)
{
  assert(this);

//  this is usually set too high and we have not yet been able to detect a closed
//  stream, thus we leave the 10 sec timeout
//  m_timeout = millisec;
}

/* GSocket_GetError:
 *  Returns the last error which occurred for this socket. Note that successful
 *  operations do not clear this back to GSOCK_NOERROR, so use it only
 *  after an error.
 */
GSocketError WXDLLIMPEXP_NET GSocket::GetError()
{
  assert(this);

  return m_error;
}

/* Callbacks */

/* GSOCK_INPUT:
 *   There is data to be read in the input buffer. If, after a read
 *   operation, there is still data available, the callback function will
 *   be called again.
 * GSOCK_OUTPUT:
 *   The socket is available for writing. That is, the next write call
 *   won't block. This event is generated only once, when the connection is
 *   first established, and then only if a call failed with GSOCK_WOULDBLOCK,
 *   when the output buffer empties again. This means that the app should
 *   assume that it can write since the first OUTPUT event, and no more
 *   OUTPUT events will be generated unless an error occurs.
 * GSOCK_CONNECTION:
 *   Connection successfully established, for client sockets, or incoming
 *   client connection, for server sockets. Wait for this event (also watch
 *   out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
 * GSOCK_LOST:
 *   The connection is lost (or a connection request failed); this could
 *   be due to a failure, or due to the peer closing it gracefully.
 */

/* GSocket_SetCallback:
 *  Enables the callbacks specified by 'flags'. Note that 'flags'
 *  may be a combination of flags OR'ed toghether, so the same
 *  callback function can be made to accept different events.
 *  The callback function must have the following prototype:
 *
 *  void function(GSocket *socket, GSocketEvent event, char *cdata)
 */
void GSocket::SetCallback(GSocketEventFlags flags,
                         GSocketCallback callback, char *cdata)
{
  int count;

  assert(this);

  for (count = 0; count < GSOCK_MAX_EVENT; count++)
  {
    if ((flags & (1 << count)) != 0)
    {
      m_cbacks[count] = callback;
      m_data[count] = cdata;
    }
  }
}

/* GSocket_UnsetCallback:
 *  Disables all callbacks specified by 'flags', which may be a
 *  combination of flags OR'ed toghether.
 */
void GSocket::UnsetCallback(GSocketEventFlags flags)
{
  int count;

  assert(this);

  for (count = 0; count < GSOCK_MAX_EVENT; count++)
  {
    if ((flags & (1 << count)) != 0)
    {
      m_cbacks[count] = NULL;
      m_data[count] = NULL;
    }
  }
}


#define CALL_CALLBACK(socket, event) {                                  \
  _GSocket_Disable(socket, event);                                      \
  if (socket->m_cbacks[event])                                          \
    socket->m_cbacks[event](socket, event, socket->m_data[event]);      \
}

int GSocket::Recv_Stream(char *buffer, int size)
{
    OTFlags flags ;
    OTResult res ;
    OTByteCount sz = 0 ;

    OTCountDataBytes( m_endpoint , &sz ) ;
    if ( size > (int)sz )
        size = sz ;
    res = OTRcv( m_endpoint , buffer , size , &flags ) ;
    if ( res < 0 )
    {
        return -1 ;
    }

    // we simulate another read event if there are still bytes
    if ( m_takesEvents )
    {
        OTByteCount sz = 0 ;
        OTCountDataBytes( m_endpoint , &sz ) ;
        if ( sz > 0 )
        {
            m_detected |= GSOCK_INPUT_FLAG ;
            (m_cbacks[GSOCK_INPUT])(this, GSOCK_INPUT, m_data[GSOCK_INPUT]);
        }
    }
    return res ;
}

int GSocket::Recv_Dgram(char *buffer, int size)
{
// TODO
  int ret = -1;
#if 0
  struct sockaddr from;
  WX_SOCKLEN_T fromlen = sizeof(from);
  GSocketError err;

  fromlen = sizeof(from);

  ret = recvfrom(m_endpoint, buffer, size, 0, &from, (WX_SOCKLEN_T *) &fromlen);

  if (ret == -1)

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -