コード例 #1
0
ファイル: UdpSocket.cpp プロジェクト: f059074251/interested
void UdpSocket::SetMulticastLoop(bool x)
{
	if (GetSocket() == INVALID_SOCKET)
	{
		CreateConnection();
	}
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
	if (IsIpv6())
	{
		int val = x ? 1 : 0;
		if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (char *)&val, sizeof(int)) == -1)
		{
			Handler().LogError(this, "SetMulticastLoop(ipv6)", Errno, StrError(Errno), LOG_LEVEL_WARNING);
		}
		return;
	}
#endif
#endif
	int val = x ? 1 : 0;
	if (setsockopt(GetSocket(), SOL_IP, IP_MULTICAST_LOOP, (char *)&val, sizeof(int)) == -1)
	{
		Handler().LogError(this, "SetMulticastLoop(ipv4)", Errno, StrError(Errno), LOG_LEVEL_WARNING);
	}
}
コード例 #2
0
ファイル: UdpSocket.cpp プロジェクト: f059074251/interested
bool UdpSocket::IsMulticastLoop()
{
	if (GetSocket() == INVALID_SOCKET)
	{
		CreateConnection();
	}
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
	if (IsIpv6())
	{
		int is_loop = 0;
		socklen_t size = sizeof(int);
		if (getsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (char *)&is_loop, &size) == -1)
		{
			Handler().LogError(this, "IsMulticastLoop(ipv6)", Errno, StrError(Errno), LOG_LEVEL_WARNING);
		}
		return is_loop ? true : false;
	}
#endif
#endif
	int is_loop = 0;
	socklen_t size = sizeof(int);
	if (getsockopt(GetSocket(), SOL_IP, IP_MULTICAST_LOOP, (char *)&is_loop, &size) == -1)
	{
		Handler().LogError(this, "IsMulticastLoop(ipv4)", Errno, StrError(Errno), LOG_LEVEL_WARNING);
	}
	return is_loop ? true : false;
}
コード例 #3
0
ファイル: baseclient.cpp プロジェクト: 10fish/heron
void BaseClient::OnConnect(ConnectionEndPoint* _endpoint, EventLoop::Status _status) {
  sp_int32 error = 0;
  socklen_t len = sizeof(error);

  // If either we got an event other that write event or the connect didnt succeed
  // we need to close shop.
  if (_status != EventLoop::WRITE_EVENT ||
      getsockopt(_endpoint->get_fd(), SOL_SOCKET, SO_ERROR, reinterpret_cast<void*>(&error), &len) <
          0 ||
      error != 0) {
    // we asked for a write event but select server delivered something else.
    // or for some reason the connect failed
    close(_endpoint->get_fd());
    delete _endpoint;
    state_ = DISCONNECTED;
    HandleConnect_Base(CONNECT_ERROR);
    return;
  }

  // Init the connection and start it
  conn_ = CreateConnection(_endpoint, &connection_options_, eventLoop_);
  if (conn_->start() != 0) {
    close(_endpoint->get_fd());
    delete conn_;
    conn_ = NULL;
    state_ = DISCONNECTED;
    HandleConnect_Base(CONNECT_ERROR);
    return;
  }

  state_ = CONNECTED;
  conn_->registerForClose([this](NetworkErrorCode s) { this->OnClose(s); });
  HandleConnect_Base(OK);
  return;
}
コード例 #4
0
ファイル: CStep.cpp プロジェクト: cdaffara/symbiandump-os1
//------------------------------------------------------------------------------------------------------
// testing
// EHrQuery
//------------------------------------------------------------------------------------------------------
TInt CPARAM_MESS_NAMEStep::do_execute(Int2Type<EHrQuery>)
{
    TInt result;

    //-- 1. Create a connection.
    result = CreateConnection();
    if(result != KErrNone)
        return result;

    result = OpenHostResolver();
    if(result != KErrNone)
    {
    //-- stop and close connection
    StopCloseConnection();
    return result;
    }

    TDnsQueryBuf      dnsQryBuf;
    TDnsRespABuf      dnsRespABuf;

    dnsQryBuf().SetType(KDnsRRTypeA);
    dnsQryBuf().SetData(_L8("http://www.sample.net/"));


    TName connName;
    result =SendReceive(EHrQuery,TIpcArgs(&dnsQryBuf,&dnsRespABuf,0,iSSRes));
    if(result != KErrNone)
        return result;

    //-- close connection
    result = CloseConnection();

    return result;
}
コード例 #5
0
ファイル: bz2-stub-dbus.c プロジェクト: google/bzip2-rpc
int BZ2_bzTestStream(int ifd, int verbosity, int small) {
  static const char *method = "BZ2_bzTestStream";
  struct DriverConnection *conn = CreateConnection();
  DBusMessage *msg = ConnectionNewRequest(conn, method);

  DBusMessageIter msg_it;
  dbus_message_iter_init_append(msg, &msg_it);
  dbus_int32_t vx;
  vx = ifd;
  dbus_message_iter_append_basic(&msg_it, DBUS_TYPE_UNIX_FD, &vx);
  vx = verbosity;
  dbus_message_iter_append_basic(&msg_it, DBUS_TYPE_INT32, &vx);
  vx = small;
  dbus_message_iter_append_basic(&msg_it, DBUS_TYPE_INT32, &vx);

  DBusError err;
  dbus_error_init(&err);
  api_("%s(%d, %d, %d) =>", method, ifd, verbosity, small);
  DBusMessage *rsp = ConnectionBlockingSendReply(conn, msg, &err);
  assert (rsp != NULL);

  DBusMessageIter rsp_it;
  dbus_message_iter_init(rsp, &rsp_it);
  assert (dbus_message_iter_get_arg_type(&rsp_it) == DBUS_TYPE_INT32);
  dbus_message_iter_get_basic(&rsp_it, &vx);
  dbus_message_iter_next(&rsp_it);
  int retval = vx;
  api_("%s(%d, %d, %d) return %d <=", method, ifd, verbosity, small, retval);
  dbus_message_unref(rsp);
  DestroyConnection(conn);
  return retval;
}
コード例 #6
0
ファイル: NDBHandlePool.cpp プロジェクト: refnum/nano
//============================================================================
//		NDBHandlePool::Open : Open the database.
//----------------------------------------------------------------------------
NStatus NDBHandlePool::Open(const NFile &theFile, NDBFlags theFlags, const NString &theVFS)
{	NDBHandlePtr		dbHandle;
	NStatus				theErr;



	// Validate our parameters and state
	NN_ASSERT(theFile.IsValid());
	NN_ASSERT(!IsOpen());
	


	// Update our state
	mFile  = theFile;
	mFlags = theFlags;
	mVFS   = theVFS;



	// Create the initial connection
	//
	// The initial connection allows us to test that we can actually open the
	// database, and may be all that we need if we're only to connect once.
	theErr = CreateConnection(dbHandle);
	NN_ASSERT_NOERR(theErr);

	mIsOpen = (dbHandle != NULL);

	if (mIsOpen)
		mPool.PushBack(dbHandle);

	return(theErr);
}
コード例 #7
0
  void ConnectionManager::Connect(const Request &notification)
  {
    QSharedPointer<Edge> edge = notification.GetFrom().dynamicCast<Edge>();
    if(!edge) {
      qWarning() << "Connection attempt not from an Edge: " <<
        notification.GetFrom()->ToString();
      return;
    }
    
    QByteArray brem_id = notification.GetData().toByteArray();
    if(brem_id.isEmpty()) {
      qWarning() << "Invalid ConnectionEstablished, no id";
      return;
    }

    Id rem_id(brem_id);
    if(_local_id < rem_id) {
      qWarning() << "We should be sending CM::Connect, not the remote side.";
      return;
    }

    QSharedPointer<Connection> old_con = _con_tab.GetConnection(rem_id);
    // XXX if there is an old connection and the node doesn't want it, we need
    // to close it
    if(old_con) {
      qDebug() << "Disconnecting old connection";
      old_con->Disconnect();
    }

    CreateConnection(edge, rem_id);
  }
コード例 #8
0
ファイル: bz2-stub-dbus.c プロジェクト: google/bzip2-rpc
const char *BZ2_bzlibVersion(void) {
  static const char *method = "BZ2_bzlibVersion";
  static const char *saved_version = NULL;
  if (saved_version) {
    api_("%s() return '%s' <= (saved)", method, saved_version);
    return saved_version;
  }

  struct DriverConnection *conn = CreateConnection();
  DBusMessage *msg = ConnectionNewRequest(conn, method);

  DBusError err;
  dbus_error_init(&err);
  api_("%s() =>", method);
  DBusMessage *rsp = ConnectionBlockingSendReply(conn, msg, &err);
  assert (rsp != NULL);

  DBusMessageIter rsp_it;
  dbus_message_iter_init(rsp, &rsp_it);
  assert (dbus_message_iter_get_arg_type(&rsp_it) == DBUS_TYPE_STRING);
  const char *retval;
  dbus_message_iter_get_basic(&rsp_it, &retval);
  dbus_message_iter_next(&rsp_it);
  api_("%s() return '%s' <=", method, retval);
  saved_version = strdup(retval);
  dbus_message_unref(rsp);
  DestroyConnection(conn);
  return saved_version;
}
コード例 #9
0
	void CDatabaseOdbcMsSqlTest::TestCase_CreateDatabase()
	{
		CLogger::LogInfo( StringStream() << "**** Start TestCase_CreateDatabase ****" );
#if defined( _WIN32 )
		InstallDatabaseMsSql( DB_DATABASE, DB_USER, DB_PASS );
		InstallSourceOdbcMsSql( DB_DATABASE );
#endif
		{
			auto const guard = make_block_guard( [this]()
			{
				DoLoadPlugins();
			}, []()
			{
				UnloadPlugins();
			} );
			std::unique_ptr< CDatabase > database( InstantiateDatabase( _type ) );

			if ( database )
			{
				DatabaseConnectionSPtr connection = CreateConnection( *database, _server, _user, _password );

				if ( connection && connection->IsConnected() )
				{
					connection->SelectDatabase( _database );
					connection->ExecuteUpdate( _createTable );
				}
			}
		}
		CLogger::LogInfo( StringStream() << "**** End TestCase_CreateDatabase ****" );
	}
コード例 #10
0
	void CDatabaseOdbcMsSqlTest::TestCase_DestroyDatabase()
	{
		CLogger::LogInfo( StringStream() << "**** Start TestCase_DestroyDatabase ****" );
#if defined( _WIN32 )
		UninstallSourceOdbcMsSql( DB_DATABASE );
		UninstallDatabaseMsSql( DB_DATABASE, DB_USER, DB_PASS );
#endif
		{
			auto const guard = make_block_guard( [this]()
			{
				DoLoadPlugins();
			}, []()
			{
				UnloadPlugins();
			} );
			std::unique_ptr< CDatabase > database( InstantiateDatabase( _type ) );

			if ( database )
			{
				DatabaseConnectionSPtr connection = CreateConnection( *database, _server, _user, _password );

				try
				{
					connection->ExecuteUpdate( QUERY_DROP_TABLE );
				}
				catch ( std::exception & )
				{
					BOOST_CHECK( false );
				}

				database->RemoveConnection();
			}
		}
		CLogger::LogInfo( StringStream() << "**** End TestCase_DestroyDatabase ****" );
	}
コード例 #11
0
ファイル: CStep.cpp プロジェクト: cdaffara/symbiandump-os1
//------------------------------------------------------------------------------------------------------
// testing
// ESRCancel
//------------------------------------------------------------------------------------------------------
TInt CPARAM_MESS_NAMEStep::do_execute(Int2Type<ESRClose>)
{
    TInt result;

    //-- 1. Create a connection.
    result = CreateConnection();
    if(result != KErrNone)
        return result;

	result = OpenServiceResolver();
    if(result != KErrNone)
		{
		//-- stop and close connection
		StopCloseConnection();
		return result;
		}

    result =SendReceive(ESRClose,TIpcArgs(0, 0, 0, iSSRes));
    if(result != KErrNone)
        return result;

    //-- close connection
    result = CloseConnection();

    return result;
}
コード例 #12
0
ファイル: UdpSocket.cpp プロジェクト: f059074251/interested
void UdpSocket::SetMulticastDefaultInterface(const std::string& intf, int if_index)
{
	if (GetSocket() == INVALID_SOCKET)
	{
		CreateConnection();
	}
#ifdef ENABLE_IPV6
#ifdef IPPROTO_IPV6
	if (IsIpv6())
	{
		struct in6_addr a;
		if (Utility::u2ip( intf, a ))
		{
			SetMulticastDefaultInterface( a, if_index );
		}
		return;
	}
#endif
#endif
	ipaddr_t a;
	if (Utility::u2ip( intf, a ))
	{
		SetMulticastDefaultInterface( a, if_index );
	}
}
コード例 #13
0
ファイル: CStep.cpp プロジェクト: cdaffara/symbiandump-os1
//------------------------------------------------------------------------------------------------------
// testing
// EHRCancel
//------------------------------------------------------------------------------------------------------
TInt CPARAM_MESS_NAMEStep::do_execute(Int2Type<EHRCancel>)
{
    TInt result;

    //-- 1. Create a connection.
    result = CreateConnection();
    if(result != KErrNone)
        return result;

    result = OpenHostResolver();
    if(result != KErrNone)
    {
    //-- stop and close connection
    StopCloseConnection();
    return result;
    }

	_LIT(KName, "www.yahoo.com");
	TBufC<20> aName(KName);

    TNameEntry aResult;

	result = SendReceive(EHRGetByName,TIpcArgs(&aName,&aResult,0, iSSRes));

    result =SendReceive(EHRCancel,TIpcArgs(0,0,0,iSSRes));
    if(result != KErrNone)
        return result;

    //-- stop and close connection
    result = StopCloseConnection();

    return result;
}
コード例 #14
0
ファイル: Database.cpp プロジェクト: Sar777/server
bool Database::Initialize(const char* infoString, int nConns /*= 1*/)
{
    // Enable logging of SQL commands (usually only GM commands)
    // (See method: PExecuteLog)
    m_logSQL = sConfig.GetBoolDefault("LogSQL", false);
    m_logsDir = sConfig.GetStringDefault("LogsDir","");
    if (!m_logsDir.empty())
    {
        if ((m_logsDir.at(m_logsDir.length()-1)!='/') && (m_logsDir.at(m_logsDir.length()-1)!='\\'))
            m_logsDir.append("/");
    }

    m_pingIntervallms = sConfig.GetIntDefault("MaxPingTime", 30) * (MINUTE * 1000);

    //create DB connections

    //setup connection pool size
    if (nConns < MIN_CONNECTION_POOL_SIZE)
        m_nQueryConnPoolSize = MIN_CONNECTION_POOL_SIZE;
    else if (nConns > MAX_CONNECTION_POOL_SIZE)
        m_nQueryConnPoolSize = MAX_CONNECTION_POOL_SIZE;
    else
        m_nQueryConnPoolSize = nConns;

    //create connection pool for sync requests
    for (int i = 0; i < m_nQueryConnPoolSize; ++i)
    {
        SqlConnection* pConn = CreateConnection();
        if (!pConn->Initialize(infoString))
        {
            delete pConn;
            return false;
        }

        m_pQueryConnections.push_back(pConn);
    }

    //create and initialize connection for async requests
    m_pAsyncConn = CreateConnection();
    if (!m_pAsyncConn->Initialize(infoString))
        return false;

    m_pResultQueue = new SqlResultQueue;

    InitDelayThread();
    return true;
}
コード例 #15
0
static int32_t Lab16(void){uint32_t i;
  char *pt = NULL;

  memcpy(appData.HostName,SERVER,strlen(SERVER));
  if(GetHostIP() == 0){
    if( (appData.SockID = CreateConnection()) < 0 ) return -1;

/* HTTP GET string. */
    strcpy(appData.SendBuff,REQUEST); 
// 1) change Austin Texas to your city
// 2) you can change metric to imperial if you want temperature in F
    /* Send the HTTP GET string to the open TCP/IP socket. */
    sl_Send(appData.SockID, appData.SendBuff, strlen(appData.SendBuff), 0);

/* Receive response */
    sl_Recv(appData.SockID, &appData.Recvbuff[0], MAX_RECV_BUFF_SIZE, 0);
    appData.Recvbuff[strlen(appData.Recvbuff)] = '\0';

/* find ticker name in response*/
    pt = strstr(appData.Recvbuff, "id");
    i = 0; 
    if( NULL != pt ){
      pt = pt + 5; // skip over id":"
      while((i<MAXLEN)&&(*pt)&&(*pt!='\"')){
        Id[i] = *pt; // copy into Id string
        pt++; i++;    
      }
    }
    Id[i] = 0;

/* find score Value in response */
    pt = strstr(appData.Recvbuff, "\"score\"");
    i = 0; 
    if( NULL != pt ){
      pt = pt + 8; // skip over "score":
      while((i<MAXLEN)&&(*pt)&&(*pt!=',')){
        Score[i] = *pt; // copy into Score string
        pt++; i++;    
      }
    }
    Score[i] = 0;

/* find edxpost in response */
    pt = strstr(appData.Recvbuff, "edxpost");
    i = 0; 
    if( NULL != pt ){
      pt = pt + 9; // skip over edxpost":
      for(i=0; i<8; i++){
        Edxpost[i] = *pt; // copy into Edxpost string
        pt++;     
      }
    }
    Edxpost[i] = 0;
    
    sl_Close(appData.SockID);
  }

  return 0;
}
コード例 #16
0
ファイル: main.cpp プロジェクト: edholland/sipcmd
PSafePtr<OpalConnection> LocalEndPoint::MakeConnection(OpalCall &call,
        const PString &remoteParty, void *userData, unsigned int options,
        OpalConnection::StringOptions *opts)
{
    std::cout << "LocalEndpoint::" << __func__ << std::endl;
    return AddConnection(CreateConnection(call, userData, options, opts));
// return OpalLocalEndPoint::MakeConnection(call, remoteParty, userData, options, opts);
}
コード例 #17
0
void nsDBusService::DoTimerCallback(nsITimer *aTimer) {
  if (aTimer == mReconnectTimer.get()) {
    nsresult rv = CreateConnection();
    if (NS_SUCCEEDED(rv)) {
      mReconnectTimer->Cancel();
      mReconnectTimer = nsnull;
    }
  }
}
コード例 #18
0
ファイル: DBClient_GUI.c プロジェクト: bochaqos/tol
DWORD WINAPI    GUI_InitIPC (BYTE GUIAdmInstance)
{
  char      _route_name[10];
  DWORD     _listener_id;
  HANDLE    _thread_handle;

  // RouterInit
  if ( ! RouterInit () )
  {
    return DB_ERROR_COMMINIT;
  }

  // Get Route id's
  sprintf (_route_name, "GUIADM%03d", GUIAdmInstance);
  if ( ! CreateConnection (_route_name, &GUIAdmRouteId) )
  {
    return DB_ERROR_COMMINIT;
  }

  // TJG  07-12-1999 : To avoid lossing of messages, the route thar receives from DBService
  //                   will hold 64Ks instead of 6Ks (default from RouterLayer)
  if ( ! SetInputBufferSize (GUIAdmRouteId, GUI_RECV_ROUTE_SOCKET_SIZE) )
  {
    return DB_ERROR_COMMINIT;
  }

  if ( ! GetConnection ("DBGUI000", &DBGUIRouteId) )
  {
    return DB_ERROR_COMMINIT;
  }

  if ( ! GetConnection ("LOGGER000", &LogRouteId) )
  {
    return DB_ERROR_COMMINIT;
  }

  // Start GUI listener thread
  //
  // NOTE: This GUI_Listener conflicts with old draw mechanism,
  //       that is, synchronous messaging between  Draw screen
  //       and DBService.
  //       When GUI_Listener is working, results must be received
  //       through an OCX control to update data.
  //
  _thread_handle = CreateThread ((LPSECURITY_ATTRIBUTES) NULL,
                                 0,
                                 (LPTHREAD_START_ROUTINE) GUI_Listener,
                                 (LPVOID) NULL,
                                 0,
                                 (LPDWORD) &_listener_id);
  if ( _thread_handle == NULL ) 
  {
    return DB_ERROR_COMMINIT;
  }

  return DB_SUCCESS;
}
コード例 #19
0
nsresult
nsDBusService::AddClient(DBusClient* client) {
  NS_ASSERTION(!mSingleClient, "Only one client supported right now");
  mSingleClient = client;
  nsresult rv = CreateConnection();
  if (NS_FAILED(rv)) {
    mSingleClient = nsnull;
  }
  return rv;
}
コード例 #20
0
ファイル: changepassword.cpp プロジェクト: tttwwy/professor
ChangePassword::ChangePassword(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ChangePassword)
{
    ui->setupUi(this);
    ui->old->setEchoMode((QLineEdit::Password));
    ui->new_2->setEchoMode((QLineEdit::Password));
    ui->new_3->setEchoMode((QLineEdit::Password));

    CreateConnection();
}
コード例 #21
0
ファイル: Client.cpp プロジェクト: ifzz/FDK
CClient::CClient(CDataCache& cache, const string& connectionString)
    : m_sender(nullptr)
    , m_cache(cache)
    , m_state(ClientState_Stopped)
    , m_connection(nullptr)
{
	m_stateEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr);
	m_connection = CreateConnection(connectionString);
	m_connection->VReceiver(this);
	m_sender = m_connection->VSender();
}
コード例 #22
0
ファイル: baseserver.cpp プロジェクト: ashvina/heron
void BaseServer::OnNewConnection(EventLoop::Status _status) {
  if (_status == EventLoop::READ_EVENT) {
    // The EventLoop indicated that the socket is writable.
    // Which means that a new client has connected to it.
    auto endPoint = new ConnectionEndPoint(options_.get_sin_family() != AF_INET);
    struct sockaddr* serv_addr = endPoint->addr();
    socklen_t addrlen = endPoint->addrlen();
    sp_int32 fd = accept(listen_fd_, serv_addr, &addrlen);
    endPoint->set_fd(fd);
    if (endPoint->get_fd() > 0) {
      // accept succeeded.

      // Set defaults
      if (SockUtils::setSocketDefaults(endPoint->get_fd()) < 0) {
        close(endPoint->get_fd());
        delete endPoint;
        return;
      }

      // Create the connection object and register our callbacks on various events.
      BaseConnection* conn = CreateConnection(endPoint, &connection_options_, eventLoop_);
      auto ccb = [conn, this](NetworkErrorCode ec) { this->OnConnectionClose(conn, ec); };
      conn->registerForClose(std::move(ccb));

      if (conn->start() != 0) {
        // Connection didn't start properly. Cleanup.
        // We assume here that this particular connection went bad, so we simply return.
        LOG(ERROR) << "Could not start the connection for read write";
        close(endPoint->get_fd());
        delete conn;
        return;
      }
      active_connections_.insert(conn);
      HandleNewConnection_Base(conn);
      return;
    } else {
      // accept failed.
      if (errno == EAGAIN) {
        // This is really odd. We thought that we had a read event
        LOG(ERROR) << "accept failed with EAGAIN when it should have worked. Ignoring";
      } else {
        LOG(ERROR) << "accept failed with errno " << errno;
      }
      close(endPoint->get_fd());
      delete endPoint;
      return;
    }
  } else {
    // What the hell, we only registered ourselves to reading
    // Just print a warning message
    LOG(WARNING) << "WARNING while expecting a read event we got " << _status;
    return;
  }
}
コード例 #23
0
ファイル: UdpSocket.cpp プロジェクト: f059074251/interested
void UdpSocket::SetMulticastTTL(int ttl)
{
	if (GetSocket() == INVALID_SOCKET)
	{
		CreateConnection();
	}
	if (setsockopt(GetSocket(), SOL_IP, IP_MULTICAST_TTL, (char *)&ttl, sizeof(int)) == -1)
	{
		Handler().LogError(this, "SetMulticastTTL", Errno, StrError(Errno), LOG_LEVEL_WARNING);
	}
}
コード例 #24
0
ファイル: qlclient.c プロジェクト: AndrewCRMartin/qlite
BOOL ReleaseLock(int id)
{
   int    sock,
          i;
   char   c, 
          cmd[MAXBUFF],
          line[MAXBUFF];
   
   if((sock = CreateConnection()) < 0)
      return(FALSE);

   /* Send a RELEASELOCK command                                        */
   sprintf(cmd, "RELEASELOCK %d.\n", id); 
   write(sock, cmd, strlen(cmd)+1);

   /* Read the response                                                 */
   i=0;
   while(read(sock, &c, 1)) 
   {
      if(c)
      {
         line[i++] = c;
         
         if (c == '.')
         {
            shutdown(sock,0); /* We've finished reading                 */
            
#ifdef REQUIRE_ACK
            /* Send an acknowledgement                                  */
            write(sock,"ACK.",4);
#endif

            line[i-1] = '\0';
            
#ifdef DEBUG
            printf("Response: %s\n", line);
#endif
            
            if(!strncmp(line, "OK", 2))
            {
               /* Close the socket connection                           */
               close(sock);
               return(TRUE);
            }
            break;
         }
      }
   }
   close(sock);

   return(FALSE);
}
コード例 #25
0
bool
NetClientConfig::Login()
{
	bool result = false;

	if (!conn)
	CreateConnection();

	if (conn)
	result = conn->Login(host_request);

	return result;
}
コード例 #26
0
ItemConnection::ItemConnection(ItemModule* source, ItemModule* target, size_t socket, QGraphicsScene* scene)
	: QGraphicsItemGroup(0, scene), mSource(source), mTarget(target), mSockets(), mChildrens()
{
	mSockets.push_back(socket);

	// set z value
	setZValue(5.0);
	// set identification data
	setData(0, Identification);

	// create connection lines
	CreateConnection();
	UpdateConnection();
}
コード例 #27
0
ファイル: sim_lcr.c プロジェクト: AK101111/LCR-Meter-Remote
int main()
{
	e4980a = CreateConnection(LCR, LCRPORT);

/*
	The following commands were used: Pl refer to the Agilent E4980a precision LCR meter.
	IssueCommand(e4980a,":SYST:PRES");		-> Preset
	IssueCommand(e4980a,":SYST:REST");		-> Reset		
	IssueCommand(e4980a,":MEM:CLE");		-> Clear Memory buffer
	IssueCommand(e4980a, "*IDN?\n");		-> Identity of Device
	IssueCommand(e4980a, ":FUNC:IMP:TYPE CSRS\n");	-> Measurement type of impedence (Ls-Rs,Cs-Rs...)
	IssueCommand(e4980a,":FREQ 1000");		-> Setting Frequency for measurment
	IssueCommand(e4980a,":VOLT:LEV 1");		-> Setting Voltage level for measurement
	IssueCommand(e4980a, "FETC:IMP:CORR?\n");	-> Fetching Impedence
*/

	IssueCommand(e4980a,":MEM:CLE");	
	IssueCommand(e4980a, "*IDN?\n");
	printf("%s\n", ReadResponse(e4980a, 10000));
	
    //	Initial Setup	
	IssueCommand(e4980a, ":FUNC:IMP:TYPE CSRS\n");
	IssueCommand(e4980a,":FREQ 1000");
	IssueCommand(e4980a,":VOLT:LEV 1");
		
    //Data recoreded will be stored in file name 1.csv in the same directory as binary file of form .out
	FILE* fp; 
	fp = fopen(OUTPUTFILE, "w");
	

	//initializing frequency sweep:
	//The frequency sweep should ideally be logarithmic, but the device limits the frequency range from 20 - 20khz
	//The following code has two parts [1000,5000,4001] and [5001,9981,250]

    int freq;
	for(freq = 0; freq <= 4000; ++freq)
        sample(freq);

	for(freq=4001; freq <= 9000; freq += 20)
        sample(freq);
	
	IssueCommand(e4980a, "*WAI\n");
			
	fprintf(fp, "%s\n", responseFromLCRMeter);
	fclose(fp);

	// Resetting .
	IssueCommand(e4980a,":FREQ 1000");
	IssueCommand(e4980a,":VOLT:LEV 0.2");
}
コード例 #28
0
ファイル: main.c プロジェクト: msakhnik/udp-client-server
int main(int argc, char** argv)
{
    
    int sock;
    SAI addr, remoteServer;

    GetServerHost((SAI *) & remoteServer, argc, argv);
    sock = CreateConnection((SAI *) & addr, sizeof (addr));

    SendMessage(sock, (SA *) & remoteServer,
                           sizeof (remoteServer), argc, argv);

    CloseConnection(sock);
    return 0;
}
コード例 #29
0
ファイル: UdpSocket.cpp プロジェクト: f059074251/interested
bool UdpSocket::IsBroadcast()
{
	int is_broadcast = 0;
	socklen_t size;

	if (GetSocket() == INVALID_SOCKET)
	{
		CreateConnection();
	}
	if (getsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *)&is_broadcast, &size) == -1)
	{
		Handler().LogError(this, "IsBroadcast", Errno, StrError(Errno), LOG_LEVEL_WARNING);
	}
	return is_broadcast != 0;
}
コード例 #30
0
ファイル: UdpSocket.cpp プロジェクト: f059074251/interested
int UdpSocket::GetMulticastTTL()
{
	int ttl = 0;
	socklen_t size = sizeof(int);

	if (GetSocket() == INVALID_SOCKET)
	{
		CreateConnection();
	}
	if (getsockopt(GetSocket(), SOL_IP, IP_MULTICAST_TTL, (char *)&ttl, &size) == -1)
	{
		Handler().LogError(this, "GetMulticastTTL", Errno, StrError(Errno), LOG_LEVEL_WARNING);
	}
	return ttl;
}