コード例 #1
0
// Message passing routine, used to send and receive a typed message
// Useful for checking the packing and unpacking of message data.
void fakeMessagePassing(TypedMessage &send, TypedMessage &recv)
{
  const int tcpPort = TEST_PORT_BASE+401;
  char ipAddr[] = "127.0.0.1";

  TcpClient tcpClient;
  TcpServer tcpServer;
  SimpleMessage msgSend, msgRecv;

  send.toTopic(msgSend);

  // Construct server

  tcpServer.init(tcpPort);

  // Construct a client
  tcpClient.init(&ipAddr[0], tcpPort);
  tcpClient.makeConnect();  // make tcp client connection

  tcpServer.makeConnect();      // make tcp server connection

  tcpClient.sendMsg(msgSend);   // send message
  tcpServer.receiveMsg(msgRecv); // physically receive message
  recv.init(msgRecv); // copy received message into reference
}
コード例 #2
0
int main(int argc, char* argv[])
{
  // Create an instance of the server
  TcpServer server = TcpServer::create_server();
  
  // Prepare the server for listening for client connections
  char* port_str = (char*) "2013"; // default port 2013
  if (argc == 2) {
    port_str = (char*) argv[1];
  }
  unsigned short port = (unsigned short) atoi(port_str);

  int server_fd = server.prepare_server_socket(port, SOCK_STREAM);
  if (server_fd  == -1) {
    cout << "Server preparation failed. Exiting application..." << endl;
    exit(1);
  }
  
  // Run the main loop
  // This method run indefinitely
  int ret = server.run_main_event_loop();
  if (ret != 0) {
    cout << "Error running the server main event loop, exiting the server process..." << endl;
  }

  // At this point we are exiting the server
  return 0;
}
コード例 #3
0
ファイル: client.cpp プロジェクト: Xiangyu-Xue/Drawpile
void Client::connectToServer(LoginHandler *loginhandler)
{
	Q_ASSERT(_isloopback);

	TcpServer *server = new TcpServer(this);
	_server = server;
	_isloopback = false;
	m_sessionId = loginhandler->sessionId(); // target host/join ID (if known already)

	connect(server, SIGNAL(loggingOut()), this, SIGNAL(serverDisconnecting()));
	connect(server, SIGNAL(serverDisconnected(QString, QString, bool)), this, SLOT(handleDisconnect(QString, QString, bool)));
	connect(server, SIGNAL(serverDisconnected(QString, QString, bool)), loginhandler, SLOT(serverDisconnected()));
	connect(server, SIGNAL(loggedIn(QString, int, bool)), this, SLOT(handleConnect(QString, int, bool)));
	connect(server, SIGNAL(messageReceived(protocol::MessagePtr)), this, SLOT(handleMessage(protocol::MessagePtr)));

	connect(server, SIGNAL(expectingBytes(int)), this, SIGNAL(expectingBytes(int)));
	connect(server, SIGNAL(bytesReceived(int)), this, SIGNAL(bytesReceived(int)));
	connect(server, SIGNAL(bytesSent(int)), this, SIGNAL(bytesSent(int)));
	connect(server, SIGNAL(lagMeasured(qint64)), this, SIGNAL(lagMeasured(qint64)));

	if(loginhandler->mode() == LoginHandler::HOST)
		loginhandler->setUserId(m_myId);

	emit serverConnected(loginhandler->url().host(), loginhandler->url().port());
	server->login(loginhandler);

	m_lastToolCtx = canvas::ToolContext();
}
コード例 #4
0
int main(int argc, char** argv)
{
  // Initialize ROS node "sm_talker"
  ros::init(argc, argv, "sm_listener");

  // Required to start timers for non-node ROS use.
  ros::Time::init();

  // Little message to know she's started
  ROS_INFO_STREAM("STARTING SM_MANAGER");

  // Create and execute manager
  // * Create a TCP server connection on TCP_PORT (see common.h)
  // * Initialize manager using server connection
  // * Initialize handler using server connection
  // * Add handler to manager
  // * Execute manager spin loop
  TcpServer server;
  server.init(TCP_PORT);

  MessageManager manager;
  MyHandler handler;

  manager.init(&server);

  // Handler initilaized with reply connection (typically the same as
  // incoming connection but now always)
  handler.init(&server);
  manager.add(&handler);
  manager.spin();

  return 0;
}
コード例 #5
0
void* TcpServer::receiveThreadFunction(void* arg){
  TcpServer* server = (TcpServer*)arg;

  while(server->initialized){
    printf("TcpServer: listening for new connection\n");

    struct sockaddr_in client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
    server->client_fd = accept(server->socket_fd, (struct sockaddr*)&client_addr, &client_addr_len);
    if (server->client_fd < 0){
      perror("TcpServer Error: accept");
      server->initialized = false;
      return 0;
    }
    printf("TcpServer: connection accepted\n");

    server->connected = true;
    while(server->isConnected()){
      server->receivePacket();
    }

    printf("TcpServer: connection closed\n");
  }

  return 0;
}
コード例 #6
0
ファイル: InetWvIn.cpp プロジェクト: ilearain/stk
void InetWvIn :: listen( int port, unsigned int nChannels,
                         Stk::StkFormat format, Socket::ProtocolType protocol )
{
    mutex_.lock();

    if ( connected_ ) delete soket_;

    if ( nChannels < 1 ) {
        oStream_ << "InetWvIn()::listen(): the channel argument must be greater than zero.";
        handleError( StkError::FUNCTION_ARGUMENT );
    }

    if ( format == STK_SINT16 ) dataBytes_ = 2;
    else if ( format == STK_SINT32 || format == STK_FLOAT32 ) dataBytes_ = 4;
    else if ( format == STK_FLOAT64 ) dataBytes_ = 8;
    else if ( format == STK_SINT8 ) dataBytes_ = 1;
    else {
        oStream_ << "InetWvIn(): unknown data type specified!";
        handleError( StkError::FUNCTION_ARGUMENT );
    }
    dataType_ = format;

    unsigned long bufferBytes = bufferFrames_ * nBuffers_ * nChannels * dataBytes_;
    if ( bufferBytes > bufferBytes_ ) {
        if ( buffer_) delete [] buffer_;
        buffer_ = (char *) new char[ bufferBytes ];
        bufferBytes_ = bufferBytes;
    }

    data_.resize( bufferFrames_, nChannels );
    lastFrame_.resize( 1, nChannels, 0.0 );

    bufferCounter_ = 0;
    writePoint_ = 0;
    readPoint_ = 0;
    bytesFilled_ = 0;

    if ( protocol == Socket::PROTO_TCP ) {
        TcpServer *socket = new TcpServer( port );
        oStream_ << "InetWvIn:listen(): waiting for TCP connection on port " << socket->port() << " ... ";
        handleError( StkError::STATUS );
        fd_ = socket->accept();
        if ( fd_ < 0) {
            oStream_ << "InetWvIn::listen(): Error accepting TCP connection request!";
            handleError( StkError::PROCESS_SOCKET );
        }
        oStream_ << "InetWvIn::listen(): TCP socket connection made!";
        handleError( StkError::STATUS );
        soket_ = (Socket *) socket;
    }
    else {
        soket_ = new UdpSocket( port );
        fd_ = soket_->id();
    }

    connected_ = true;

    mutex_.unlock();
}
コード例 #7
0
ファイル: TcpServer.cpp プロジェクト: KingsleyYau/PushServer
void* TcpServer::RecvParse(void* pData)
{
    TcpServer* pthis = NULL;
    mio2_t m = NULL;
    LPMESSAGE_DATA pMsg = NULL;
    int iLen = 0;

    if (pData) {
        m = ((c2s_t)pData)->mio2;
        pthis = (TcpServer*)(((c2s_t)pData)->pvoid);
    }
    if (!pthis || !m) {
        gvLog(LOG_ERR_SYS, "(TcpServer::RecvParse) receive pool start fail by error param");
        return NULL;
    }

    RecvParser* pRecvParser = new RecvParser();
    if (!pRecvParser) return NULL;

    LPMESSAGE_DATA pErrMsgData = NULL;
    while (pthis->IsRunning()) {
        pMsg = g_MsgListRecv->Get_Msg();
        if (pMsg) {
            gvLog(LOG_MSG, "(TcpServer::RecvParse) entering receive parser... iFd:%d", pMsg->iFd);
            iLen = pRecvParser->ParserData(pMsg);
            gvLog(LOG_MSG, "(TcpServer::RecvParse) MSG: iLen:%d iFd:%d", iLen, pMsg->iFd);
            if (iLen > 0) {
                //put into data parser
                pthis->AddConnect();

                pMsg = MatchPacketHandler::GetInstance()->Handling(pMsg, pErrMsgData);
                if (NULL != pMsg){
                    g_MsgListData->Put_Msg(pMsg);
                }
                else if (NULL != pErrMsgData){
                    pErrMsgData->bSendAndClose = true;
                    g_MsgListSnd->Put_Msg(pErrMsgData);
                }
                else {
                    if (NULL != pMsg) {
                        gvLog(LOG_MSG, "(TcpServer::RecvParse) MSG: MatchPacketHandler() iFd:%d", pMsg->iFd);
                    }
                }
            } else {
                if (iLen == 0) {
                    //maybe (errno == EWOULDBLOCK || errno == EINTR || errno == EAGAIN)
                    gvLog(LOG_MSG, "(TcpServer::RecvParse) (iLen == 0) iFd:%d", pMsg->iFd);
                } else {
                    gvLog(LOG_MSG, "(TcpServer::RecvParse) mio2_close iFd:%d", pMsg->iFd);
                    mio2_close(m, pMsg->iFd);
                }
                gvLog(LOG_MSG, "(TcpServer::RecvParse) MSG: fail iFd:%d pMsg:%p", pMsg->iFd, pMsg);
                PutIdleMsgBuff(pMsg);
            }
            gvLog(LOG_MSG, "(TcpServer::RecvParse) left receive parser... pMsg:%p", pMsg);
        }
        usleep(1);
    }
}
コード例 #8
0
int main(void)
{
	
	TcpServer ts;
	ts.start();
	
	return 0;
}
コード例 #9
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    TcpServer w;
    w.show();
    
    return a.exec();
}
コード例 #10
0
ファイル: TcpSocketImpl.cpp プロジェクト: 3Nigma/frayon
void TcpSocketImpl::accept(TcpServer& server, const TcpSocketOptions& o)
{
    int fd = server.impl().accept(o);

    bool inherit = false;
    System::IODeviceImpl::open(fd, inherit);

    log_debug( "accepted " << server.impl().fd() << " => " << this->fd() );
}
コード例 #11
0
ファイル: main.cpp プロジェクト: aleandr100/Snake
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    TcpServer *server = new TcpServer(2);

    server->startServer();

    return a.exec();
}
コード例 #12
0
ファイル: tcpServer.cpp プロジェクト: jacres/logger
void TcpServer::OnCloseClient( uv_handle_t* handle ) {
  Client& client = *( static_cast<Client*>( handle->data ) );
  TcpServer* socket = client.p_server;
  client.b_connected = false;

  socket->DisposeClient( client.id );

  if ( socket->m_close_client_callback ) {
    socket->m_close_client_callback( client.id );
  }
}
コード例 #13
0
ファイル: main.cpp プロジェクト: xxg1413/NetworkProgramming
int main(void)
{

	TcpServer *server = new TcpServer();

	server->Start();

	free(server);

	return 0;
}
コード例 #14
0
ファイル: common.cpp プロジェクト: owenpanqiufeng/ZLMediaKit
API_EXPORT int API_CALL initRtspServer(unsigned short port) {
	s_pRtspSrv.reset(new TcpServer<RtspSession>());
	try {
		s_pRtspSrv->start(port);
		return 0;
	} catch (std::exception &ex) {
		s_pRtspSrv.reset();
		WarnL << ex.what();
		return -1;
	}
}
コード例 #15
0
ファイル: main.cpp プロジェクト: gonboy/Ubuntu-chatroom
int main( int argc, char **argv )
{
   	
    QApplication a( argc, argv );
    QTranslator translator(0);
    translator.load("tcpserver_zh",".");
    a.installTranslator(&translator);    
    
    TcpServer *tcpserver = new TcpServer();
    tcpserver->show();
    return a.exec();
}
コード例 #16
0
	void TcpServer::_listen_cb( int fd, short events, void * arg )
	{
		if(events & EV_READ)
		{
			TcpServer * server = (TcpServer *)arg;
			server->Accept();
		}
		else if(events & EV_WRITE)
		{
			TcpServer * server = (TcpServer *)arg;
			event_base_loopbreak(server->_base);
		}
	}
コード例 #17
0
ファイル: tcpServer.cpp プロジェクト: jacres/logger
void TcpServer::OnNewConnection( uv_stream_t* server_stream, int status ) {
  assert( status == 0 );
  TcpServer* server = static_cast<TcpServer*>( server_stream->data );

  if ( status == -1 ) {
  } else {
    int client_id = server->Accept();

    if ( client_id && server->m_new_client_callback ) {
      server->m_new_client_callback( client_id );
    }
  }
}
コード例 #18
0
 void onClientConnected(FramedTcpConnection *con)
 {
   cout << "Client " << con->remoteHost() << ":"
        << con->remotePort() << " connected, "
        << server->numberOfClients() << " clients connected\n";
   con->frameReceived.connect(mem_fun(*this, &MyClass::onFrameReceived));
 }
コード例 #19
0
ファイル: tcpServer.cpp プロジェクト: jacres/logger
void TcpServer::OnRead( uv_stream_t* stream, ssize_t num_read, const uv_buf_t* buf ) {
  Client* client = static_cast<Client*>( stream->data );
  TcpServer* server = client->p_server;

  if ( num_read < 0 ) {
    uv_close( reinterpret_cast<uv_handle_t*>( stream ), TcpServer::OnCloseClient );
    delete buf->base;
    return;
  }

  if ( server->m_read_callback ) {
    server->m_read_callback( client->id, buf->base, num_read );
  }

  delete buf->base;
}
コード例 #20
0
 void onClientDisconnected(FramedTcpConnection *con,
                           FramedTcpConnection::DisconnectReason reason)
 {
   cout << "Client " << con->remoteHost().toString() << ":"
        << con->remotePort() << " disconnected,"
        << server->numberOfClients() << " clients connected\n";
   /* Don't delete the con object, the TcpServer will do it */
 }
コード例 #21
0
ファイル: TcpServer.cpp プロジェクト: Hukuma23/WS
err_t TcpServer::staticAccept(void *arg, tcp_pcb *new_tcp, err_t err)
{
	TcpServer* con = (TcpServer*)arg;

	if (con == NULL)
	{
		debugf("NO CONNECTION ON TCP");
		//closeTcpConnection(new_tcp);
		tcp_abort(new_tcp);
		return ERR_ABRT;
	}
	else
		con->sleep = 0;

	err_t res = con->onAccept(new_tcp, err);
	return res;
}
コード例 #22
0
ファイル: common.cpp プロジェクト: owenpanqiufeng/ZLMediaKit
API_EXPORT void API_CALL onAppStart(){
	static onceToken s_token([](){
		Logger::Instance().add(std::make_shared<ConsoleChannel>("stdout", LTrace));
		EventPoller::Instance(true);

		cleaner::Instance().push_back([](){
			s_pRtspSrv.reset();
			s_pRtmpSrv.reset();
			s_pHttpSrv.reset();
			WorkThreadPool::Destory();
			UDPServer::Destory();
			AsyncTaskThread::Destory();
			EventPoller::Destory();
			DebugL << "clear common" << endl;
			Logger::Destory();
		});
	},nullptr);
}
コード例 #23
0
ファイル: server.cpp プロジェクト: zwy1135/ChatForHomework
int main()
{

	int mainserver;
	WORD sockVersion = MAKEWORD(2,2);  
    WSADATA wsaData;  
    if(WSAStartup(sockVersion, &wsaData)!=0)  
    {  
        return 0;  
    }  
	cout<<"mainserver?"<<endl;
	cin>>mainserver;

	TcpServer server = TcpServer(bool(mainserver));
	server.runserver();


}
コード例 #24
0
int main()
{
    Log::rootLog().setLevel(Log::ERROR);
    
    TcpServer s;
    
    s.setRunCallback(std::bind(&onServerRun, _1));
    
    HttpServer httpd(&s);

    httpd.setHttpCallback("/", std::bind(&onHandler, _1, _2));

    httpd.listen(Address(11181));

    s.start(8);

    return 0; 
}
コード例 #25
0
TcpServer *TcpServerBalancer::createServer(CWsgiEngine *engine)
{
    TcpServer *server;
    if (m_sslConfiguration) {
#ifndef QT_NO_SSL
        auto sslServer = new TcpSslServer(m_serverName, m_protocol, m_wsgi, engine);
        sslServer->setSslConfiguration(*m_sslConfiguration);
        server = sslServer;
#endif //QT_NO_SSL
    } else {
        server = new TcpServer(m_serverName, m_protocol, m_wsgi, engine);
    }
    connect(engine, &CWsgiEngine::shutdown, server, &TcpServer::shutdown);

    if (m_balancer) {
        connect(engine, &CWsgiEngine::started, this, [=] () {
            m_servers.push_back(server);
            resumeAccepting();
        }, Qt::QueuedConnection);
        connect(server, &TcpServer::createConnection, server, &TcpServer::incomingConnection, Qt::QueuedConnection);
    } else {

#ifdef Q_OS_LINUX
        if (m_wsgi->reusePort()) {
            connect(engine, &CWsgiEngine::started, this, [=] () {
                int socket = listenReuse(m_address, m_port, true);
                if (!server->setSocketDescriptor(socket)) {
                    qFatal("Failed to set server socket descriptor, reuse-port");
                }
            }, Qt::DirectConnection);
            return server;
        }
#endif

        if (server->setSocketDescriptor(socketDescriptor())) {
            server->pauseAccepting();
            connect(engine, &CWsgiEngine::started, server, &TcpServer::resumeAccepting, Qt::DirectConnection);
        } else {
            qFatal("Failed to set server socket descriptor");
        }
    }

    return server;
}
コード例 #26
0
ファイル: TcpServer.cpp プロジェクト: KingsleyYau/PushServer
/*
int TcpServer::_c2s_client_mio_callback(mio_t m, mio_action_t a, int fd, void *data, void *arg)
*/
int TcpServer::_c2s_client_mio2_callback(mio2_t m, mio2_action_t a, int fd, void *data, void *arg)
{
    TcpServer* pthis = NULL;
    c2s_t c2s = NULL;
    if (arg) {
        c2s = (c2s_t)arg;
        pthis = (TcpServer*)(((c2s_t)arg)->pvoid);
    }

    switch(a) {
        /*
        case action_READ:
        */
        case mio2_action_READ:
            //do NOT accept new connect while restart
            if (pthis->IsRestarting()) {
				return 0;
            }
            return pthis->RevData(fd, m);
        /*
        case action_WRITE:
        */
        case mio2_action_WRITE:
            /*
            return 0;
            */
            return 1;
        /*
        case action_CLOSE:
        */
        case mio2_action_CLOSE:
            return 0;
        /*
        case action_ACCEPT:
        */
        case mio2_action_ACCEPT:
            //c2s->highfd = GetHighfd(m);
            gvLog(LOG_MSG, "(TcpServer::_c2s_client_mio_callback) Accept connect IP=%s(%d)...", data, fd);
            //add by using epoll
            return 1;
    }
    return 0;
}
コード例 #27
0
void ServerTCP()
{
    TcpListenSocket listen;
    TcpServer server;
    Packet data;
    string source;
    data.SetByteOrder(CX_PACKET_BIG_ENDIAN);
    // Tests non-blocking TCP connections.  If listen socket is non-blocking
    // then all TCP connections generated will be non-blocking.
    if(!listen.InitializeSocket(PORT, 5U, 0U, 0U, 1, 1)) 
    {
        cout << "Unable to initialize listen socket on port " << PORT << endl;
        return;
    }
    cout << "Initialized TCP Listen Socket\n";
    cout << "Waiting for a connection.... ";
    while( true ) 
    {
        if(listen.AwaitConnection(server))
        {
            cout << "Connection Made!\n";

            while(true)
            {
                if(server.Recv(data, 50, 0) > 0) //  Receive up to 50 bytes to packet.
                { 
                    cout << "Received: ";
                    char val;
                    while(data.Read(val))
                    {
                        cout << val;
                        server.Send(data);
                    }
                    cout << endl;
                }
                CxUtils::SleepMs(1);
            }
            cout << "Connection Closed.\n";
        }
        SleepMs(1);
    }
}
コード例 #28
0
int main()
{
    TcpServer server;

    if (server.listen(2000) != AbstractSocket::Done)
    {
        perror("Error :");
        return -1;
    }

    TcpSocket* s = server.accept();

    if (s == NULL)
    {
        cout << "Error: cannot accept conection" << endl;
        return -1;
    }

    cout << "Connected client" << endl;
    int i = 4;
    i++;
    cout << "Remote host : " << s->getRemotePort() << endl;
    cout << s->getLocalPort() << endl;
    cout << server.getRemoteAddress().toString() << endl;
    cout << s->getRemoteAddress().toString() << endl;
    s->sendInt32(10);
    sleep(2);
    s->sendString("hello");
    s->sendCharArray("world", 5);
    Frame f;
    f << "This is a frame " << 666 << '\n';

    if (s->sendFrame(f) != AbstractSocket::Done)
        perror("error on send frame");

    delete s;
    server.close();
    s->close();
    return 1;
}
コード例 #29
0
ファイル: TcpServer.cpp プロジェクト: KingsleyYau/PushServer
void* TcpServer::MioRun(void *pData)
{
    TcpServer* pthis = NULL;
    mio2_t m = NULL;
    if (pData) {
        m = ((c2s_t)pData)->mio2;
        pthis = (TcpServer*)(((c2s_t)pData)->pvoid);
    }
    if (!pthis || !m) {
        gvLog(LOG_ERR_SYS, "(TcpServer::MioRun) mio run start fail by error param");
        return NULL;
    }

    while (pthis->IsRunning()) {
        {
            CAutoLock lock(&(pthis->m_tMutexMio));
            mio2_run(m, 5);
        }
        usleep(1);
    }
    return NULL;
}
コード例 #30
0
ファイル: TcpServer.cpp プロジェクト: KingsleyYau/PushServer
void* TcpServer::DataParse(void* pData)
{
    TcpServer* pthis = NULL;
    mio2_t m = NULL;
    LPMESSAGE_DATA pMsg = NULL;
    DataParser* pDataParser = NULL;

    if (pData) {
        m = ((c2s_t)pData)->mio2;
        pthis = (TcpServer*)(((c2s_t)pData)->pvoid);
    }
    if (!pthis || !m) {
        gvLog(LOG_ERR_SYS, "(TcpServer::DataParse) process pool start fail by error param");
        return NULL;
    }

    pDataParser = new DataParser();
    if (!pDataParser) goto ErrDataParse;

    while (pthis->IsRunning() && !pthis->IsRestarting()) {
        pMsg = g_MsgListData->Get_Msg();
        if (pMsg) {
            gvLog(LOG_MSG, "(TcpServer::DataParse) entering data parser...");
            pDataParser->ParserData(pMsg);
            gvLog(LOG_MSG, "(TcpServer::DataParse) left data parser...");
            g_MsgListSnd->Put_Msg(pMsg);
        }
        usleep(1);
    }

ErrDataParse:
//    if (pVerDBMapping) {
//        pVerDBMapping->UnInit();
//        delete pVerDBMapping;
//    }
    if (pDataParser) {
        delete pDataParser;
    }
}