Ejemplo n.º 1
0
bool SocketTest::tcpSocketTest()
{
    SimpleServer server;
    server.start();
    System::Sleep(500);
    TEST_ASSERT(server.start_flag)
    TEST_ASSERT_MSG(server.bind_flag, server.msg.text())
    TEST_ASSERT_MSG(!server.aborted, server.msg.text())
    // create tcp socket
    TcpSocket client;
    client.connect(TCP_TEST_HOST, TCP_TEST_PORT);
    TEST_ASSERT(client.getRemoteAddress().getPort() == TCP_TEST_PORT);
    client.send(TEST_MESSAGE1);
    TEST_ASSERT_MSG(!server.aborted, server.msg.text())
    System::Sleep(100);
    TEST_ASSERT_MSG(!server.aborted, server.msg.text())    
    TEST_ASSERT(server.msg1_flag)
    // test if something is already running on a port
    Socket psocket;
    TEST_THROWS(psocket.bind(TCP_TEST_PORT), Net::Errors::SocketException);
    
    String in;
    client.readUntil(in, '!');
    TEST_ASSERT(in == TEST_MESSAGE2);
    client.readUntil(in, '.', 2000);
    TEST_ASSERT_MSG(in == TEST_MESSAGE3, in.text());
    client.readUntil(in, '!', 2000);
    TEST_ASSERT(in == TEST_MESSAGE4);
    client.readUntil(in, "#@", 2000);
    TEST_ASSERT(in == TEST_MESSAGE5);
    return true;
}
Ejemplo n.º 2
0
bool readLinesFromClientTest(const int linesize=TcpSocket::DEFAULT_MAX_MSG){
    cout << "Starting readLinesFromClientTest(" << linesize << ") ...\n";
    string message("Passaro verde abandona ninho. \nEscuto!\n");

    pid_t child;
    // client code
    if ((child=fork())==0){
        try {
            TcpSocket toServer;
            cout << "  Forked child waiting a bit\n";
            sleep(1);
            cout << "  Forked child connecting to server\n";
            toServer.connect("127.0.0.1",LOCALPORT);
            cout << "  Forked child connected: " << toServer << endl;
            cout << "  Forked child sending to server\n";
            toServer.writeline(message);
            cout << "  Forked child closing connection to server\n";
            toServer.close();
            cout << "  Forked child exiting\n";
            exit(0);
        } catch (std::exception& e) {
            cout << "  Forked child exception: " << e.what() << endl;
            exit(-1);
        }
        return false; // for clarity
    }

    // server code
    TcpSocket* connectedSocket;
    try {
        TcpSocket serverSocket;
        connectedSocket = bindListenAccept(LOCALPORT, serverSocket);
        std::string clientmessage;
        cout << "  Reading one (at most " << linesize << " chars long) line from client\n";

        // Read a line
        connectedSocket->setMaxReceive(linesize);
        while ((*connectedSocket) >> clientmessage);
        if (clientmessage.empty())
            throw std::runtime_error("clinet message is empty");

        cout << "  Read: \"" << clientmessage << "\"\n";
        if (!(clientmessage.compare(message) == 0)){
            
            throw std::runtime_error("Messages dont match");
        }
        checkChild(child);
        serverSocket.close();
        connectedSocket->close();
        cout << "Done!\n";
        delete connectedSocket;
        return true;
    } catch (std::exception& e) {
        cout << "  Server exception: " << e.what() << endl;
        cout << "Failed!\n";
        checkChild(child, true);
        delete connectedSocket;
        return false;
    }
}
Ejemplo n.º 3
0
void client()
{
	TcpSocket socket;
	Socket::Status status = socket.connect(IpAddress::getLocalAddress(), DH_PORT);
	
	if (status != Socket::Status::Done)
	{
		perror("connection to server failed");
		return;
	}
	
	mpz_t secret;
	CurveRef curve = client_receive_curve(socket);
	PointRef p = client_create_key(socket, curve, secret);
	client_send_key(socket, p);
	PointRef remoteKey = client_receive_key(socket);
	PointRef sharedSecret = PointCreateMultiple(remoteKey, secret, curve);
	
	char *desc = PointCreateDescription(sharedSecret);
	cout << "Secret: " << desc << endl;
    free(desc);
	
    mpz_clear(secret);
    CurveDestroy(curve);
    PointDestroy(p);
    PointDestroy(remoteKey);
    PointDestroy(sharedSecret);
	
	socket.disconnect();
}
Ejemplo n.º 4
0
        void run()
        {
            TcpSocket socket;
            socket.connect("127.0.0.1", mPort);

            T::Send(socket, mValue);
        }
Ejemplo n.º 5
0
void c_communication(c_serveur& sett)
{
    TcpSocket svr;
    svr.connect(sett.c_ip,55001);
    c_infoPlayer<<c_pseudo;
    svr.send(c_infoPlayer);



    cout<<"Communication lancee"<<endl;
    while(c_connected)
        {
            c_attendre.lock();
            svr.send(c_sortant);
            c_sortant.clear();
            c_sortant<<false<<"";
            c_attendre.unlock();
            bool a;
            string b;
            if(svr.receive(c_entrant) == Socket::Done)
            {
                //system("cls");
                c_entrant>>a>>b;
                if(!a)
                c_msgsRecus = b;

            }
            else
            {
Ejemplo n.º 6
0
bool sendReceiveObjectTest(){
    cout << "sendReceiveObjectTest() ...\n";

    Object tosend('c', 34, true, "cinco");

    pid_t child;
    // client code
    if ((child=fork())==0){
        try {
            TcpSocket toServer;
            cout << "  Forked child waiting a bit\n";
            sleep(1);
            cout << "  Forked child connecting to server\n";
            toServer.connect("127.0.0.1",LOCALPORT);
            cout << "  Forked child connected: " << toServer << endl;
            cout << "  Forked child sending to server\n";
            toServer.write(reinterpret_cast<char *>(&tosend), sizeof(Object));
            cout << "  Forked child closing connection to server\n";
            toServer.close();
            cout << "  Forked child exiting\n";
            exit(0);
        } catch (std::exception& e) {
            cout << "  Forked child exception: " << e.what() << endl;
            exit(-1);
        }
        return false; // for clarity
    }
    // server code
    TcpSocket* connectedSocket;
    try {
        TcpSocket serverSocket;
        connectedSocket = bindListenAccept(LOCALPORT, serverSocket);
        std::string clientmessage;
        cout << "  Reading one object from client\n";

        // Read the object
        Object received;
        int len = connectedSocket->read(reinterpret_cast<char *>(&received), sizeof(Object));
        cout << "  Read: " << len << " bytes from " << *connectedSocket << endl;
        if (!(tosend.compare(received) == 0))
            throw std::runtime_error("objects dont match");
        cout << "  Server read " << received << endl;
        
        checkChild(child);
        serverSocket.close();
        connectedSocket->close();
        cout << "Done!\n";
        delete connectedSocket;
        return true;
    } catch (std::exception& e) {
        cout << "  Server exception: " << e.what() << endl;
        cout << "Failed!\n";
        checkChild(child, true);
        delete connectedSocket;
        return false;
    }
}
Ejemplo n.º 7
0
        void run()
        {
            TcpSocket socket;
            socket.connect("127.0.0.1", mPort);

            TcpInt32TestSender::Send(socket, mIntValue);
            TcpStringTestSender::Send(socket, mStringValue);
            TcpFloatTestSender::Send(socket, mFloatValue);
            TcpBoolTestSender::Send(socket, mBoolValue);
        }
Ejemplo n.º 8
0
int main()
{

	socket.receive(recvChar, 1024, received);
	cout << recvChar << endl;

	Socket::Status status = socket.connect("localhost", 10006);
	socket.send(sendChar, 1024);

	return 0;
}
int main(void) {
    TcpSocket servSocket;
    servSocket.create();
    servSocket.connect("127.0.0.1", 9999);
    Message msg;
    msg.add("type", "login");
    msg.add("user", "root");
    msg.add("pwd", "root");

    servSocket << msg;

    servSocket.close();
    return 0;
}
Ejemplo n.º 10
0
void Client::own_thread()
{
    TcpSocket sock;
    sock.connect( m_host, m_port );

    unsigned int version = 1;
    unsigned int options = 0;

    sock.send( version );
    sock.send( options );
    // first send size of name.
    sock.sendString( m_name );

    unsigned int images = 0;
    unsigned int width = 0;
    unsigned int height = 0;
    unsigned int bpp = 0;
    try
    {
        sock.receive( images );
        sock.receive( width );
        sock.receive( height );
        sock.receive( bpp );
    } catch( std::string a_error )
    {
        std::cerr << a_error << std::endl;
        return ;
    }
    std::cout << "DEBUG: " << "images: " << images << " w: " << width << " h: " << height << " bpp: " << bpp << std::endl;

    std::unique_ptr< sepia::Writer > data = std::unique_ptr< sepia::Writer >( new sepia::Writer( m_name, images, width, height, bpp ) );


    int more = 0; // more data available if true.
    while( !m_terminate )
    {
        for( int i = 0; i < data->getGroupHeader()->count; i++ )
        {
            sock.receive( *data->getHeader( i ) );
            sock.receive( data->getAddress( i ), data->getSize( i ) );
        }
        data->update();
    }
}
Ejemplo n.º 11
0
bool simpleAcceptConnectTest(){
    cout << "Starting simpleAcceptConnectTest() ...\n";
    pid_t child;
    // client code
    if ((child=fork())==0){
        try {
            TcpSocket toServer;
            cout << "  Forked child waiting a bit\n";
            sleep(1);
            cout << "  Forked child connecting to server\n";
            toServer.connect("127.0.0.1",LOCALPORT);
            cout << "  Forked child connected: " << toServer << endl;
            cout << "  Forked child closing connection to server\n";
            toServer.close();
            cout << "  Forked child exiting\n";
            exit(0);
        } catch (TcpSocket::SocketException& e) {
            cout << "  Forked child exception: " << e.what() << endl;
            exit(-1);
        }
        return false; // for clarity
    }
    // server code
    TcpSocket* toClient;
    try {
        TcpSocket serverSocket;
        toClient = bindListenAccept(LOCALPORT, serverSocket);
        cout << "  Server closing connection to client\n";
        toClient->close();
        cout << "  Server closing listening socket\n";
        serverSocket.close();
        checkChild(child);
        cout << "Done!\n";
        delete toClient;
        return true;
    } catch (std::exception& e) {
        cout << "  Server exception: " << e.what() << endl;
        cout << "Failed!\n";
        checkChild(child, true);
        delete toClient;
        return false;
    }
}
Ejemplo n.º 12
0
int main()
{

	Socket::Status status = socket.connect("localhost", 10004);
	socket.send(sendChar, 1024);

	buidMap();

	/////build threads
	Thread sendrecvThread(&sendRecv);
	Thread mainGameThread(&mainGame);
	Thread pressButtonThread(&pressButton);

	/////launch threads
	sendrecvThread.launch();
	pressButtonThread.launch();
	mainGameThread.launch();
	/////////////////////////////////////
	return 0;
}
Ejemplo n.º 13
0
void client()
{
	TcpSocket socket;
	Socket::Status status = socket.connect(IpAddress::getLocalAddress(), ECDSA_PORT);
	
	if (status != Socket::Status::Done)
	{
		perror("connection to server failed");
		return;
	}
    
	CurveRef curve = client_receive_curve(socket);
    PointRef pubKey = receive_key(socket);
	bool r = dsa_receive_and_verify_message(socket, curve, pubKey);
	cout << "Result: " << r << endl;
    
    CurveDestroy(curve);
    PointDestroy(pubKey);
    
    socket.disconnect();
}
Ejemplo n.º 14
0
bool RedisProxy::run(const HostAddress& addr)
{
    if (isRunning()) {
        return false;
    }

    if (m_vipEnabled) {
        TcpSocket sock = TcpSocket::createTcpSocket();
        Logger::log(Logger::Message, "connect to vip address(%s:%d)...", m_vipAddress, addr.port());
        if (!sock.connect(HostAddress(m_vipAddress, addr.port()))) {
            Logger::log(Logger::Message, "set VIP [%s,%s]...", m_vipName, m_vipAddress);
            int ret = NonPortable::setVipAddress(m_vipName, m_vipAddress, 0);
            Logger::log(Logger::Message, "set_vip_address return %d", ret);
        } else {
            m_vipSocket = sock;
            m_vipEvent.set(eventLoop(), sock.socket(), EV_READ, vipHandler, this);
            m_vipEvent.active();
        }
    }


    m_monitor->proxyStarted(this);
    Logger::log(Logger::Message, "Start the %s on port %d", APP_NAME, addr.port());

    RedisCommand cmds[] = {
        {"HASHMAPPING", 11, -1, onHashMapping, NULL},
        {"ADDKEYMAPPING", 13, -1, onAddKeyMapping, NULL},
        {"DELKEYMAPPING", 13, -1, onDelKeyMapping, NULL},
        {"SHOWMAPPING", 11, -1, onShowMapping, NULL},
        {"POOLINFO", 8, -1, onPoolInfo, NULL},
        {"SHUTDOWN", 8, -1, onShutDown, this}
    };
    RedisCommandTable::instance()->registerCommand(cmds, sizeof(cmds)/sizeof(RedisCommand));

    return TcpServer::run(addr);
}
Ejemplo n.º 15
0
bool SmtpClient::sendMail(Url* url, Mail* mail)
{
   bool rval = false;

   // ensure mail has recipients
   if(mail->getRecipients()->length() == 0)
   {
      ExceptionRef e = new Exception(
         "No mail recipients specified.",
         "monarch.mail.NoMailRecipients");
      e->getDetails()["sender"] =
         mail->getSender()["smtpEncoding"]->getString();
      e->getDetails()["subject"] =
         mail->getMessage()["headers"]["Subject"]->getString();
      Exception::set(e);
   }
   else
   {
      // connect, use 30 second timeouts
      TcpSocket s;
      s.setReceiveTimeout(30000);
      Exception::clear();
      InternetAddress address(url->getHost().c_str(), url->getPort());
      if(Exception::isSet())
      {
         ExceptionRef e = new Exception(
            "Failed to setup SMTP host address.",
            "monarch.mail.SmtpAddressLookupFailure");
         e->getDetails()["host"] = url->getHost().c_str();
         e->getDetails()["port"] = url->getPort();
         Exception::push(e);
         rval = false;
      }
      else if(s.connect(&address, 30))
      {
         // create smtp connection
         Connection c(&s, false);

         // send mail
         rval = sendMail(&c, mail);

         // disconnect
         c.close();

         if(!rval)
         {
            ExceptionRef e = new Exception(
               "Failed to send mail.",
               "monarch.mail.MailSendFailed");
            e->getDetails()["host"] = url->getHost().c_str();
            e->getDetails()["port"] = url->getPort();
            Exception::push(e);
         }
      }
      else
      {
         ExceptionRef e = new Exception(
            "Failed to connect to SMTP host.",
            "monarch.mail.SmtpConnectionFailure");
         e->getDetails()["host"] = url->getHost().c_str();
         e->getDetails()["port"] = url->getPort();
         Exception::push(e);
         rval = false;
      }
   }

   return rval;
}