void getDeviceState (double start_proxyxform[], bool &start_proxybutton, double end_proxyxform[], bool &end_proxybutton) {
    cout << "receive?" << endl;
    if (receiver.recv(buf)) {
        while (receiver.recv(buf));
        
        cout << buf << endl;
        
        boost::split(vectbuf, buf, boost::is_any_of("\n"));
        parse(vectbuf[0], vect1);
        parse(vectbuf[1], vect2);
        /*
        int i;
        for (i=0;i<vect1.size();i++)
        cout << vect1[i] << endl;
        for (i=0;i<vect1.size();i++)
        cout << vect2[i] << endl;
        */
        // Extract transform matrix
        for (i=0; i<16; i++) {
            start_proxyxform[i] = boost::lexical_cast<double>(vect1[i].c_str());
            end_proxyxform[i]   = boost::lexical_cast<double>(vect2[i].c_str());
        }
        //cout << vect1[16] << "\t" << vect2[16] << endl;
        start_proxybutton = boost::lexical_cast<int>(vect1[16].c_str()); //? true : false;
        end_proxybutton   = boost::lexical_cast<int>(vect2[16].c_str()); //? true : false;
    }
}
Example #2
0
void test_bring_up_down() {
    NetworkInterface* net = MBED_CONF_APP_OBJECT_CONSTRUCTION;

    for (int i = 0; i < COUNT; i++) {
        int err = MBED_CONF_APP_CONNECT_STATEMENT;
        TEST_ASSERT_EQUAL(0, err);

        printf("MBED: IP Address %s\r\n", net->get_ip_address());
        TEST_ASSERT(net->get_ip_address());

        UDPSocket udp;
        err = udp.open(net);
        TEST_ASSERT_EQUAL(0, err);
        err = udp.close();
        TEST_ASSERT_EQUAL(0, err);

        TCPSocket tcp;
        err = tcp.open(net);
        TEST_ASSERT_EQUAL(0, err);
        err = tcp.close();
        TEST_ASSERT_EQUAL(0, err);

        err = net->disconnect();
        TEST_ASSERT_EQUAL(0, err);
    }
}
Example #3
0
/**
 * Use a connection, checking that it is good
 * Checks via doing an NTP transaction
 */
static void use_connection(OnboardCellularInterface *driver)
{
    const char *ip_address = driver->get_ip_address();
    const char *net_mask = driver->get_netmask();
    const char *gateway = driver->get_gateway();

    TEST_ASSERT(driver->is_connected());

    TEST_ASSERT(ip_address != NULL);
    tr_debug("IP address %s.", ip_address);
    TEST_ASSERT(net_mask != NULL);
    tr_debug("Net mask %s.", net_mask);
    TEST_ASSERT(gateway != NULL);
    tr_debug("Gateway %s.", gateway);

    UDPSocket sock;
    SocketAddress host_address;

    TEST_ASSERT(driver->gethostbyname(MBED_CONF_APP_ECHO_SERVER, &host_address) == 0);
    host_address.set_port(MBED_CONF_APP_ECHO_UDP_PORT);

    tr_debug("UDP: Server %s address: %s on port %d.",
             MBED_CONF_APP_ECHO_SERVER, host_address.get_ip_address(),
             host_address.get_port());

    TEST_ASSERT(sock.open(driver) == 0)

    sock.set_timeout(10000);
    do_udp_echo(&sock, &host_address, 1);

    sock.close();
}
Example #4
0
int main (void) {
    MBED_HOSTTEST_TIMEOUT(20);
    MBED_HOSTTEST_SELECT(udpecho_server_auto);
    MBED_HOSTTEST_DESCRIPTION(UDP echo server);
    MBED_HOSTTEST_START("NET_5");

    EthernetInterface eth;
    eth.init(); //Use DHCP
    eth.connect();
    printf("MBED: Server IP Address is %s:%d\r\n", eth.getIPAddress(), ECHO_SERVER_PORT);

    UDPSocket server;
    server.bind(ECHO_SERVER_PORT);

    Endpoint client;
    char buffer[BUFFER_SIZE] = {0};
    printf("MBED: Waiting for packet...\r\n");
    while (true) {
        int n = server.receiveFrom(client, buffer, sizeof(buffer));
        if (n > 0) {
            //printf("Received packet from: %s\n", client.get_address());
            const int buffer_string_end_index = n >= BUFFER_SIZE ? BUFFER_SIZE-1 : n;
            buffer[buffer_string_end_index] = '\0';
            //printf("Server received: %s\n", buffer);
            server.sendTo(client, buffer, n);
        }
    }
}
void UDPSOCKET_SENDTO_TIMEOUT()
{
    char tx_buffer[100];
    fill_tx_buffer_ascii(tx_buffer, sizeof(tx_buffer));

    UDPSocket sock;
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.open(get_interface()));

    SocketAddress udp_addr;
    get_interface()->gethostbyname(MBED_CONF_APP_ECHO_SERVER_ADDR, &udp_addr);
    udp_addr.set_port(9);

    Timer timer;
    timer.start();
    int sent = sock.sendto(udp_addr, tx_buffer, sizeof(tx_buffer));
    timer.stop();
    TEST_ASSERT_EQUAL(sizeof(tx_buffer), sent);
    TEST_ASSERT(timer.read_ms() <= 100);

    timer.reset();
    timer.start();
    sent = sock.sendto(udp_addr, tx_buffer, sizeof(tx_buffer));
    timer.stop();
    TEST_ASSERT_EQUAL(sizeof(tx_buffer), sent);
    TEST_ASSERT(timer.read_ms() <= 100);
    printf("MBED: Time taken: %fs\n", timer.read());

    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock.close());
}
Example #6
0
void UDPSOCKET_BIND_ADDRESS()
{
#if MBED_CONF_NSAPI_SOCKET_STATS_ENABLE
    int count = fetch_stats();
    for (int j = 0; j < count; j++) {
        TEST_ASSERT_EQUAL(SOCK_CLOSED,  udp_stats[j].state);
    }
#endif

    UDPSocket *sock = new UDPSocket;
    if (!sock) {
        TEST_FAIL();
    }
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock->open(NetworkInterface::get_default_instance()));
    SocketAddress sockAddr = SocketAddress(NetworkInterface::get_default_instance()->get_ip_address(), 80);
    nsapi_error_t bind_result = sock->bind(sockAddr);
    if (bind_result == NSAPI_ERROR_UNSUPPORTED) {
        TEST_IGNORE_MESSAGE("bind() not supported");
    } else {
        TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, bind_result);
    }

    delete sock;

#if MBED_CONF_NSAPI_SOCKET_STATS_ENABLE
    count = fetch_stats();
    for (int j = 0; j < count; j++) {
        TEST_ASSERT_EQUAL(SOCK_CLOSED, udp_stats[j].state);
    }
#endif
}
Example #7
0
/* ===  FUNCTION  ==============================================================
 *         Name:  listenerFlow
 *  Description:  The pig listens for incoming messages here. This is the only
 *                way to trigger events on a pig. Everything on the pig is in
 *                response to some message.
 * =============================================================================
 */
static void listenerFlow (int listenerPort)
{

  gPigOwnNode.portNumber = listenerPort;
  UDPSocket listenSocket (COM_IP_ADDR, listenerPort);

  while (true)
  {
    // Block for msg receipt
    int inMsgSize;
    char *inMsg;
    inMsg = (char *)malloc (MAX_MSG_SIZE);
    memset(inMsg, 0, MAX_MSG_SIZE);
    try
    {
      inMsgSize = listenSocket.recv(inMsg, MAX_MSG_SIZE);
    }
    catch (SocketException &e)
    {
      cout<<gPigOwnNode.portNumber<<": "<<e.what()<<endl;
    }
    inMsg[inMsgSize] = '\0';

    thread handlerThread (pigMsgHandler, inMsgSize, inMsg);
    handlerThread.detach();
  }
}		/* -----  end of function listenerFlow  ----- */
int main(int argc, char *argv[]) {
  if ((argc < 4) || (argc > 5)) {   // Test for correct number of arguments
    cerr << "Usage: " << argv[0] 
         << " <Destination Address> <Destination Port> <Send String> [<TTL>]\n";
    exit(1);
  }

  string servAddress = argv[1];         // First arg: multicast address
  unsigned short port = atoi(argv[2]);  // Second arg: port
  char* sendString = argv[3];           // Third arg: string to echo

  unsigned char multicastTTL = 1;       // Default TTL
  if (argc == 5) {
    multicastTTL = atoi(argv[4]);       // Command-line TTL
  }

  try {
    UDPSocket sock;

    sock.setMulticastTTL(multicastTTL);

    // Repeatedly send the string to the server
    for (;;) {
      sock.sendTo(sendString, strlen(sendString), servAddress, port);
      sleep(3);
    }
  } catch (SocketException &e) {
    cerr << e.what() << endl;
    exit(1);
  }

  return 0;
}
Example #9
0
void
WatchDog::continuousStatusReport( std::string theStateMsg) {
    if (_myContinuousStateChangeIP != "" && _myContinuousStateChangePort != -1) {
        try {
            AC_DEBUG << "send State: " << theStateMsg;
            UDPSocket * myUDPClient = 0;
            Unsigned32 inHostAddress = getHostAddress(_myContinuousStateChangeIP.c_str());
            // try to find a free client port between _myContinuousStateChangePort+1 and MAX_PORT
            for (unsigned int clientPort = _myContinuousStateChangePort+1; clientPort <= MAX_PORT; clientPort++)
            {
                try {
                    myUDPClient = new UDPSocket(INADDR_ANY, clientPort);
                    break;
                }
                catch (SocketException & ) {
                    myUDPClient = 0;
                }
            }
            if (myUDPClient) {
                myUDPClient->sendTo(inHostAddress, _myContinuousStateChangePort, theStateMsg.c_str(), theStateMsg.size());
                delete myUDPClient;
            }
        }
        catch (Exception & ) {
            _myLogger.logToFile(std::string("Sorry, cannot establish socket connection to ip: '") + _myContinuousStateChangeIP + "'");            
        }
    }
}
Example #10
0
void udp_server_task(void const *argument)
{
    DigitalOut indicator(LED1);
    UDPSocket server;

    server.bind(ECHO_SERVER_PORT);
    // printf("[udp_server_task] Start\r\n");

    Endpoint client;
    char buffer[BUFFER_SIZE] = { 0 };
    while (true) {
        //printf("[udp_server_task] Wait for packet...\r\n");
        int n = server.receiveFrom(client, buffer, sizeof(buffer));
        if (n > 0) {
            //printf("[udp_server_task] Received packet from: %s\r\n", client.get_address());
            const int buffer_string_end_index = n >= BUFFER_SIZE ? BUFFER_SIZE - 1 : n;
            buffer[buffer_string_end_index] = '\0';
            //printf("[udp_server_task] Server received: %s\r\n", buffer);
            if (host_port == 0) {
                strcpy(host_address, client.get_address());
                host_port = ECHO_SERVER_PORT + 1;
                //printf("[udp_server_task] Set host address and port: %s:%d\r\n", host_address, host_port);
            }
            // Dispatch data to client for sending to test HOST
            cli_serv_mutex.lock(); // LOCK
            // Push to datagram queue
            datagram_queue.push_front(std::string(buffer));
            max_queue_len = datagram_queue.size() > max_queue_len ? datagram_queue.size() : max_queue_len;
            received_packets++;
            cli_serv_mutex.unlock(); // LOCK
            indicator = !indicator;
        }
    }
}
Example #11
0
int main(int argc, char *argv[]) {
  if ((argc < 3) || (argc > 4)) {   // Test for correct number of arguments
    cerr << "Usage: " << argv[0] 
         << " <Destination Address> <Destination Port> <Send String>\n";
    exit(1);
  }

  string destAddress = argv[1];             // First arg:  destination address
  unsigned short destPort = atoi(argv[2]);  // Second arg: destination port
  char* sendString = argv[3];               // Third arg:  string to broadcast

  try {
    UDPSocket sock;
  
    // Repeatedly send the string (not including \0) to the server
    for (;;) {
      sock.sendTo(sendString, strlen(sendString), destAddress, destPort);
      sleep(3);
    }
  } catch (SocketException &e) {
    cerr << e.what() << endl;
    exit(1);
  }
  
  return 0;
}
Example #12
0
void udp_client_task(void const *argument)
{
    while (host_port == 0) {
        // Waiting for HOST port notification
    }

    DigitalOut indicator(LED2);
    UDPSocket socket;
    socket.init();

    Endpoint echo_server;
    echo_server.set_address(host_address, host_port);
    //printf("[udp_client_task] Start: %s:%d\r\n", host_address, host_port);

    while (1) {
        std::string datagram;
        bool sent_datagram = false;
        cli_serv_mutex.lock(); // LOCK
        if (datagram_queue.size() > 0) {
            // POP from datagram queue
            datagram = datagram_queue.back();
            datagram_queue.pop_back();
            sent_datagram = true;
        }
        cli_serv_mutex.unlock(); // LOCK
        if (sent_datagram) {
            //printf("[udp_client_task] Forwarded datagram: %s\r\n", datagram.c_str());
            socket.sendTo(echo_server, (char *)datagram.c_str(), datagram.length());
            forwarded_packets++;
            indicator = !indicator;
        }
    }
}
void CTunnelingConnection::HandleDisconnectRequest(unsigned char* buffer)
{	
	CDisconnectRequest dis_req(buffer);
	if(dis_req.GetChannelID() != _state._channelid){
		return;
	}

	CDisconnectResponse dis_resp(_state._channelid,E_NO_ERROR);
	unsigned char buf[256];
	dis_resp.FillBuffer(buf,256);
	UDPSocket sock;

	LOG_DEBUG("[Send] [BUS] [Disconnect Response]");
	
	sock.SendTo(buf,dis_resp.GetTotalSize(),_device_control_address,_device_control_port);
	
	_heartbeat->Close();

	JTCSynchronized s(*this);
        _state._channelid = 0;
        _state._recv_sequence = 0;
        _state._send_sequence = 0;

        SetStatusDisconnected();
}
Example #14
0
void PairingHandler::sendPairRequest() {    
    // grab the node socket from the NodeList singleton
    UDPSocket *nodeSocket = NodeList::getInstance()->getNodeSocket();
    
    // prepare the pairing request packet
    
    // use the getLocalAddress helper to get this client's listening address
    int localAddress = getLocalAddress();
    
    char pairPacket[24] = {};
    sprintf(pairPacket, "Find %d.%d.%d.%d:%hu",
            localAddress & 0xFF,
            (localAddress >> 8) & 0xFF,
            (localAddress >> 16) & 0xFF,
            (localAddress >> 24) & 0xFF,
            NodeList::getInstance()->getSocketListenPort());
    
    qDebug("Sending pair packet: %s\n", pairPacket);
    
    sockaddr_in pairingServerSocket;
    
    pairingServerSocket.sin_family = AF_INET;
    
    // lookup the pairing server IP by the hostname
    struct hostent* hostInfo = gethostbyname(PAIRING_SERVER_HOSTNAME);
    memcpy(&pairingServerSocket.sin_addr, hostInfo->h_addr_list[0], hostInfo->h_length);
    pairingServerSocket.sin_port = htons(PAIRING_SERVER_PORT);
    
    // send the pair request to the pairing server
    nodeSocket->send((sockaddr*) &pairingServerSocket, pairPacket, strlen(pairPacket));
}
Example #15
0
TEST(Reflection, Variable)
{
	AM_DECLARE_VAR(g_instance, int, "MyInteger", 2);
	ASSERT_TRUE(g_instance == 2);
	
	g_instance = 3;
	ASSERT_TRUE(g_instance == 3);

	AM_ASSIGN_VAR("MyInteger", 4);
	ASSERT_TRUE(g_instance == 4);
	
	AM_ASSIGN_VAR_STR("MyInteger", "5");
	ASSERT_TRUE(g_instance == 5);
	
	UDPWriteDesc writeDesc;
	writeDesc.port = 5005;
	writeDesc.address = "localhost";
	std::string str = "MyInteger 6";
	UDPSocket writeSocket;
	ASSERT_TRUE(writeSocket.connect(writeDesc));
	ASSERT_EQ(writeSocket.write(str.c_str(), str.length()), str.length());
	std::this_thread::sleep_for(std::chrono::seconds(1));
	ASSERT_TRUE(g_instance == 6);
	GlobalVariableHandler::destroyInstance();
	
}
void UDPSOCKET_BIND_ADDRESS_PORT()
{
#if MBED_CONF_NSAPI_SOCKET_STATS_ENABLE
    int count = fetch_stats();
    for (int j = 0; j < count; j++) {
        TEST_ASSERT_EQUAL(SOCK_CLOSED,  udp_stats[j].state);
    }
#endif

    UDPSocket *sock = new UDPSocket;
    if (!sock) {
        TEST_FAIL();
    }
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock->open(get_interface()));
    TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock->bind(get_interface()->get_ip_address(), 80));

    delete sock;

#if MBED_CONF_NSAPI_SOCKET_STATS_ENABLE
    count = fetch_stats();
    for (int j = 0; j < count; j++) {
        TEST_ASSERT_EQUAL(SOCK_CLOSED, udp_stats[j].state);
    }
#endif
}
Example #17
0
    UDPSocket UDPSocket::Create(std::int32_t domain)
    {
        UDPSocket socket;
        socket.Init(domain);

        return socket;
    }
Example #18
0
/**
 * Check that we send OSC messages correctly.
 */
void OSCNodeTest::testSendBlob() {
  // First up create a UDP socket to receive the messages on.
  // Port 0 means 'ANY'
  IPV4SocketAddress socket_address(IPV4Address::Loopback(), 0);
  // Bind the socket, set the callback, and register with the select server.
  OLA_ASSERT_TRUE(m_udp_socket.Bind(socket_address));
  m_udp_socket.SetOnData(NewCallback(this, &OSCNodeTest::UDPSocketReady));
  OLA_ASSERT_TRUE(m_ss.AddReadDescriptor(&m_udp_socket));
  // Store the local address of the UDP socket so we know where to tell the
  // OSCNode to send to.
  OLA_ASSERT_TRUE(m_udp_socket.GetSocketAddress(&socket_address));

  // Setup the OSCTarget pointing to the local socket address
  OSCTarget target(socket_address, TEST_OSC_ADDRESS);
  // Add the target to the node.
  m_osc_node->AddTarget(TEST_GROUP, target);
  // Send the data
  OLA_ASSERT_TRUE(m_osc_node->SendData(TEST_GROUP, OSCNode::FORMAT_BLOB,
                  m_dmx_data));

  // Run the SelectServer this will return either when UDPSocketReady
  // completes, or the abort timeout triggers.
  m_ss.Run();

  // Remove target
  OLA_ASSERT_TRUE(m_osc_node->RemoveTarget(TEST_GROUP, target));
  // Try to remove it a second time
  OLA_ASSERT_FALSE(m_osc_node->RemoveTarget(TEST_GROUP, target));

  // Try to remove the target from a group that doesn't exist
  OLA_ASSERT_FALSE(m_osc_node->RemoveTarget(TEST_GROUP + 1, target));
}
Example #19
0
SInt64 ProxyTask::Run()
{
    const UInt32 kMaxRTCPPacketSize = 2048;
    char thePacketBuffer[kMaxRTCPPacketSize];
    QTSS_PacketStruct thePacketStruct;
    thePacketStruct.packetTransmitTime = QTSS_Milliseconds();
    thePacketStruct.packetData = thePacketBuffer;

    (void)this->GetEvents();    

    OSMutexLocker locker(sSocketPool->GetMutex());
    for (OSQueueIter iter(sSocketPool->GetSocketQueue()); !iter.IsDone(); iter.Next())
    {
        UInt32 theRemoteAddr = 0;
        UInt16 theRemotePort = 0;

        UDPSocketPair* thePair = (UDPSocketPair*)iter.GetCurrent()->GetEnclosingObject();
        Assert(thePair != NULL);
        
        for (UInt32 x = 0; x < 2; x++)
        {
            QTSS_WriteFlags theFlags = qtssWriteFlagsNoFlags;
            
            UDPSocket* theSocket = NULL;
            if (x == 0)
            {
                theFlags = qtssWriteFlagsIsRTP;
                theSocket = thePair->GetSocketA();
            }
            else
            {
                theFlags = qtssWriteFlagsIsRTCP;
                theSocket = thePair->GetSocketB();
            }
            
            Assert(theSocket->GetDemuxer() != NULL);
            OSMutexLocker locker(theSocket->GetDemuxer()->GetMutex());
            
            //get all the outstanding packets for this socket
            while (true)
            {
                UInt32 thePacketLen = 0;
                theSocket->RecvFrom(&theRemoteAddr, &theRemotePort, thePacketStruct.packetData, 
                                kMaxRTCPPacketSize, &thePacketLen);
                if (thePacketLen == 0)
                    break;//no more packets on this socket!
                    
                ProxyDemuxerTask* theDemuxerTask = (ProxyDemuxerTask*)theSocket->GetDemuxer()->GetTask(theRemoteAddr, 0);
                if (theDemuxerTask != NULL)
                {
                    QTSS_RTPStreamObject theStream = theDemuxerTask->GetStream();
                    (void)QTSS_Write(theStream, &thePacketStruct, thePacketLen, NULL, theFlags);
                }
            }
        }
    }
    return kProxyTaskPollIntervalMsec;
}
Example #20
0
int
main(int argc, char** argv)
{
  if (argc < 4)
  {
    std::fprintf(stderr, "Usage: %s <destination host> <destination port> <entity> <true|false>\n", argv[0]);
    return 1;
  }

  Address dest(argv[1]);

  // Parse port.
  unsigned port = 0;
  if (!castLexical(argv[2], port))
  {
    fprintf(stderr, "ERROR: invalid port '%s'\n", argv[2]);
    return 1;
  }

  if (port > 65535)
  {
    fprintf(stderr, "ERROR: invalid port '%s'\n", argv[2]);
    return 1;
  }

  IMC::EntityParameter p;
  p.name = "Active";
  p.value = argv[4];

  IMC::SetEntityParameters msg;
  msg.name = argv[3];
  msg.params.push_back(p);
  msg.setTimeStamp();

  uint8_t bfr[1024] = {0};
  uint16_t rv = IMC::Packet::serialize(&msg, bfr, sizeof(bfr));

  UDPSocket sock;
  try
  {
    sock.write(bfr, rv, dest, port);

    fprintf(stderr, "Raw:");
    for (int i = 0; i < rv; ++i)
      fprintf(stderr, " %02X", bfr[i]);
    fprintf(stderr, "\n");

    msg.toText(std::cerr);
  }
  catch (std::runtime_error& e)
  {
    std::cerr << "ERROR: " << e.what() << std::endl;
    return 1;
  }

  return 0;
}
void connectionInit() {
    // Initialize sockets
    if(!receiver.create())
        cout << "error creating server socket" << endl;
    if(!receiver.bind(RECEIVE_PORT))
        cout << "error binding to port " << RECEIVE_PORT << endl;
    //receiver.set_non_blocking(true);
    receiver.set_timeout(0);             // using recv()    
}
Example #22
0
/* ===  FUNCTION  ==============================================================
 *         Name:  sendMsg
 *  Description:  This function sends the given msg to the give port
 * =============================================================================
 */
void sendMsg(char *outMsg, int outMsgSize, unsigned short int destPort)
{
  try {
    static UDPSocket sendSocket;
    sendSocket.sendTo(outMsg, outMsgSize, COM_IP_ADDR, destPort);
  } catch (SocketException &e) {
    cout<<"db: Cannot send msg"<<endl;
  }
  return;
}   /* -----  end of function sendMsg  ----- */
Example #23
0
void ethSetup()
{
    EthernetInterface eth;
    eth.init(); //Use DHCP
    eth.connect();
    printf("IP Address is %s\n", eth.getIPAddress());

    udp.init();
    udp.bind(5683);

    udp.set_blocking(false, 10000);
}
Example #24
0
int BufferManager::read(UDPSocket &sock)
{
    int ret ;
    
    m_InReq.ioBuf = NULL;
    memset(&m_InReq.m_msgHeader,0,HEADER_SIZE);
    m_iLen = HEADER_SIZE;
    
    if((ret = sock.readSocket(((char *)(&m_InReq.m_msgHeader)),HEADER_SIZE,m_InReq.oppoAddr)) < 0)
    {
        handleSyscallError("BufferManager::read UDPSocket");
        return FAILED;
    }
    
    else if((unsigned int) ret < HEADER_SIZE)
    {
        handleSyscallError("BufferManager::read(UDPSocket)");
        return FAILED;
    }

    m_iLen = m_InReq.m_msgHeader.length;
    if(m_iLen == 0)
    {
        m_InReq.ioBuf = NULL;
        if(m_pAgent)
            m_pAgent->readBack(m_InReq);

        return SUCCESSFUL;
    }
    
    m_InReq.ioBuf = new char[m_iLen + 1];
    memset(m_InReq.ioBuf,0,m_iLen + 1);
    if((ret =  sock.readSocket(m_InReq.ioBuf,m_iLen,m_InReq.oppoAddr)) < 0)
    {
        handleSyscallError("BufferManager::read UDPSocket data");
        return FAILED;
    }

    if((unsigned int)ret < m_iLen)
    {
        handleError("BufferManager::read UDPSocket data incomplete");
    }
    
    if(m_pAgent)
        m_pAgent->readBack(m_InReq);
    else
        handleError("BufferManager don't be relate with a Agent");

    delete [] (char *)m_InReq.ioBuf;
    m_bInit = true;
    
    return SUCCESSFUL;
}
Example #25
0
File: main.cpp Project: betzw/mbed
void drop_bad_packets(UDPSocket &sock, int orig_timeout)
{
    nsapi_error_t err;
    sock.set_timeout(0);
    while (true) {
        err = sock.recvfrom(NULL, 0, 0);
        if (err == NSAPI_ERROR_WOULD_BLOCK) {
            break;
        }
    }
    sock.set_timeout(orig_timeout);
}
Example #26
0
/// Tries to get UDP address on non existing server, must time out
int testNonExistingServer () {
	TestHelper helper;
	UDPSocket socket;
	socket.bind();

	UDPEchoClient client(socket);
	client.result() = memFun (&helper, &TestHelper::callback);
	client.start ("127.0.0.1", 80, 1000); // Note: Port 80 won't respond
	bool hasResult = helper.waitForResult (2000);
	tcheck (hasResult, "Must callback for timeout");
	tcheck (helper.result() == error::TimeOut, "Must timeout");
	return 0;
}
void UDPSOCKET_OPEN_CLOSE_REPEAT()
{
    UDPSocket *sock = new UDPSocket;
    if (!sock) {
        TEST_FAIL();
    }

    for (int i = 0; i < 2; i++) {
        TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock->open(get_interface()));
        TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, sock->close());
    }
    delete sock;
}
int client_main(int argc, char *argv[])
{
	if ((argc < 3) || (argc > 4))
	{   // Test for correct number of arguments
		std::cerr << "Usage: " << argv[0]
			<< " <Server> <Echo String> [<Server Port>]\n";
		exit(1);
	}

	std::string servAddress = argv[1];             // First arg: server address
	char* echoString = argv[2];               // Second arg: string to echo
	int echoStringLen = strlen(echoString);   // Length of string to echo
	if (echoStringLen > ECHOMAX)
	{    // Check input length
		std::cerr << "Echo string too long" << std::endl;
		exit(1);
	}
	unsigned short echoServPort = Socket::ResolveService(
		(argc == 4) ? argv[3] : "echo", "udp");

	try
	{
		UDPSocket sock;

		// Send the string to the server
		sock.SendTo(echoString, echoStringLen, servAddress, echoServPort);

		// Receive a response
		char echoBuffer[ECHOMAX + 1];       // Buffer for echoed string + \0
		int respStringLen;                  // Length of received response
		if ((respStringLen = sock.Receive(echoBuffer, ECHOMAX)) != echoStringLen)
		{
			std::cerr << "Unable to receive" << std::endl;
			exit(1);
		}

		echoBuffer[respStringLen] = '\0';             // Terminate the string!
		std::cout << "Received: " << echoBuffer << std::endl;   // Print the echoed arg

													  // Destructor closes the socket

	}
	catch (SocketException &e)
	{
		std::cerr << e.what() << std::endl;
		exit(1);
	}

	return 0;
}
Example #29
0
int main(int argc,char **argv) {
  ALvoid *data;
  ALsizei bits,freq,size;
  ALenum format;
  ALboolean success;
  // Default packet size (in bytes)
  // Note that this doesn't necessarily have to have anything to do with the
  // buffer size of the receiver. Just set it to something appropriate
  // (depending on the connection), and the receiver will take care of the
  // playing the sound correctly...
  unsigned int packetsize=10000;
  const char defaultfile[]="bee.wav";
  const char *filename;

  if(argc>1)
    filename=argv[1];
  else
    filename=defaultfile;
  if(argc>2)
    packetsize=atoi(argv[2]);

  try {
    success=alutLoadWAV(filename,&data,&format,&size,&bits,&freq);
    std::cerr << "Bits:  " << bits << " Freq: " << freq << std::endl;

    if(success==AL_FALSE) {
      std::cerr << "Error loading " << filename << "\n";
      exit(1);
    }

    UDPSocket socket;
    socket.setPeer(InetHostAddress("127.0.0.1"),33333);

    int totalsent=0;
    while(totalsent<size) {
      // Send data in packets with a 60 ms delay between packets
      if((totalsent+packetsize)>size)
	      packetsize=size-totalsent;
      totalsent+=socket.send((char *)data+totalsent,packetsize);
      ost::Thread::sleep(60);
    }

    free(data);
  } catch(...) {
    std::cerr << "Error caught!\n";
  }

  return 0;
}
Example #30
0
void UDPSOCKET_BIND_UNOPENED()
{
    UDPSocket *sock = new UDPSocket;
    if (!sock) {
        TEST_FAIL();
    }
    nsapi_error_t bind_result = sock->bind(1024);
    if (bind_result == NSAPI_ERROR_UNSUPPORTED) {
        TEST_IGNORE_MESSAGE("bind() not supported");
    } else {
        TEST_ASSERT_EQUAL(NSAPI_ERROR_NO_SOCKET, bind_result);
    }

    delete sock;
}