• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C++ TcpSocket类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中TcpSocket的典型用法代码示例。如果您正苦于以下问题:C++ TcpSocket类的具体用法?C++ TcpSocket怎么用?C++ TcpSocket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了TcpSocket类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: ReadData

    virtual int ReadData(int fd)
    {
        int err = 0;
        int clientFd = -1;
        std::string ip;
        int port = 0;

        do {
            err = mListenSocket->Accept(clientFd, ip, port);
            if (0 != err) {
                break;
            }

            TcpSocket *clientSocket = new TcpSocket();
            err = clientSocket->Create(clientFd);
            if (0 != err) {
                break;
            }
            
            debug_log("accpeter accept client " << ip << ":" << port);
            clientSocket->SetAddr(ip, port);

            AcceptContext *ctx = new AcceptContext(clientSocket);
            mNetService->Enqueue(ctx);
            OperContext::DecRef(ctx);

        } while(0);

        return 0;
    }
开发者ID:bymzy,项目名称:rpc,代码行数:30,代码来源:Accepter.hpp


示例2: c_communication

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
            {
开发者ID:Gthebeast,项目名称:Bac_a_sable_SFML2,代码行数:29,代码来源:client.cpp


示例3: client

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();
}
开发者ID:Ceylo,项目名称:CryptoA5,代码行数:30,代码来源:client.cpp


示例4: ASSERT_THROW

void TcpSocketServer::broadcast(DataToSend* data)
{
	if (data == NULL) return;

	if (data->getType() != DataToSend::DS_READER)
	{
		for (Clients::iterator itr = _clients.begin(), end = _clients.end(); itr != end; ++itr)
		{
			TcpSocket* client = *itr;
			client->send(data);
		}
	}
	else
	{
		Ref<StreamReader> reader = data->getReader();
		ASSERT_THROW(reader->isSeekable(), EX_NOT_SUPPORTED);

		size_t pos = reader->tell();

		for (Clients::iterator itr = _clients.begin(), end = _clients.end(); itr != end; ++itr)
		{
			reader->seek(pos);
			TcpSocket* client = *itr;
			client->send(data);
		}
	}
}
开发者ID:noriter,项目名称:nit,代码行数:27,代码来源:Socket.cpp


示例5: dabInputSlipThread

void* dabInputSlipThread(void* args)
{
    dabInputSlipData* data = (dabInputSlipData*)args;
    TcpSocket* client;

    while ((client = data->server->accept()) != NULL) {
        int size = 0;
        etiLog.log(info, "SLIP server got a new client.\n");

#ifdef _WIN32
        WaitForSingleObject(data->semWrite, INFINITE);
                WaitForSingleObject(data->semQueue, INFINITE);
#else
        sem_wait(&data->semWrite);
        sem_wait(&data->semQueue);
#endif
        UdpPacket* packet = data->packets[data->nbPackets];
#ifdef _WIN32
        ReleaseSemaphore(data->semQueue, 1, NULL);
#else
        sem_post(&data->semQueue);
#endif

        while ((size = client->read(packet->getData(), packet->getSize()))
                    > 0) {
            packet->setLength(size);
#ifdef _WIN32
            WaitForSingleObject(data->semQueue, INFINITE);
#else
            sem_wait(&data->semQueue);
#endif
            data->nbPackets++;
#ifdef _WIN32
            ReleaseSemaphore(data->semQueue, 1, NULL);
#else
            sem_post(&data->semQueue);
#endif
            
#ifdef _WIN32
            WaitForSingleObject(data->semWrite, INFINITE);
            WaitForSingleObject(data->semQueue, INFINITE);
#else
            sem_wait(&data->semWrite);
            sem_wait(&data->semQueue);
#endif
            packet = data->packets[data->nbPackets];
#ifdef _WIN32
            ReleaseSemaphore(data->semQueue, 1, NULL);
#else
            sem_post(&data->semQueue);
#endif
        }
        etiLog.log(info, "SLIP server client deconnected.\n");
        client->close();
    }
    etiLog.log(error, "SLIP thread can't accept new client (%s)\n",
            inetErrDesc, inetErrMsg);

    return NULL;
}
开发者ID:DarkDare,项目名称:ODR-DabMux,代码行数:60,代码来源:dabInputSlip.cpp


示例6: sizeof

//======================================================================================
TcpSocket* TcpSocket::Accept() {
	struct sockaddr_in sa;
	socklen_t len = sizeof(sa);
	Log.i(SOCK_TAG, "TcpSocket::Accept m_iSocket=%u", m_iSocket);
	int ret = accept(m_iSocket, (struct sockaddr*) &sa, &len);
	if (-1 == ret){
		Log.e(SOCK_TAG, "TcpSocket::Accept -1!");
		return NULL;
	}
	if (0 == ret) {
		Log.e(SOCK_TAG, "TcpSocket::Accept 0!");
		return NULL;
	}

	TcpSocket *pNew = new TcpSocket(m_pSelector);
	pNew->m_iSocket = ret;
	//pNew->m_ip = ntohl(sa.sin_addr.s_addr);
	//pNew->m_iPort = ntohs(sa.sin_port);
	pNew->m_ip = sa.sin_addr.s_addr;
	pNew->m_iPort = sa.sin_port;
	pNew->m_bConnected = true;
	pNew->m_iLastRecvTime = SelectorEPoll::getInstance().m_iHaoMiao;
	pNew->setTimeout(m_iTimeout);
	pNew->SetNBlock();
	Log.i(SOCK_TAG, "TcpSocket accept %s:%u", ip2str(pNew->m_ip), pNew->m_iPort);
	return pNew;
}
开发者ID:JuannyWang,项目名称:learn,代码行数:28,代码来源:TcpSocket.cpp


示例7: run

        void run()
        {
            TcpSocket socket;
            socket.connect("127.0.0.1", mPort);

            T::Send(socket, mValue);
        }
开发者ID:afrueh,项目名称:capu,代码行数:7,代码来源:TcpSocketInputStreamTest.cpp


示例8: onHeadersComplete

int onHeadersComplete(http_parser *parser)
{   
    TcpSocket *socket = static_cast<TcpSocket*>(parser->data);
#ifndef NO_LOG
    sLog(LogEndpoint::LogLevel::DEBUG) << " === parsed header ====";
    const QHash<QString, QSharedPointer<QString>> &headers = socket->getHeader().getHeaderInfo();

    QHash<QString, QSharedPointer<QString>>::const_iterator i = headers.constBegin();
    while (i != headers.constEnd())
    {
        sLog(LogEndpoint::LogLevel::DEBUG) << i.key() << *(i.value().data());
        ++i;
    }
    sLog(LogEndpoint::LogLevel::DEBUG) << " === ============= ====";
    sLogFlush();
#endif
    QWeakPointer<QString> host = socket->getHeader().getHeaderInfo("Host");

    if (!host.isNull())
    {
        socket->getHeader().setHost(*host.data());
    }

    return 0;
}
开发者ID:shi-yan,项目名称:Swiftly,代码行数:25,代码来源:Worker.cpp


示例9: TcpSocket

/**
 *函数介绍:有请求连接,新建一个socket
 *输入参数:int socketId,新建socket的SocketDescriptor
 *返回值:无
 */
void TcpServer::incomingConnection(int socketId)
{
    TcpSocket *socket = new TcpSocket(socketId,this);
	//设置socket描述符
    socket->setSocketDescriptor(socketId);
	//写入系统日志
	//Global::systemLog->append(tr("网络通信服务端有新的连接请求"), QString(tr("服务端接收新的连接请求,socket描述符 = %1.")).arg(socketId), SystemLog::INFO);

    qDebug()<<"服务端有新的连接,socketDescriptor:"<<socket->socketDescriptor();
    //新建了一个socket连接
    addServerSocket(socketId);


    //获得客户端数据
    connect(socket, SIGNAL(haveReadDataSignal(QByteArray,int)), this, SLOT(getClientMessage(QByteArray,int)));
	//信号槽:跟踪服务端Socket状态
    connect(socket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),this,SLOT(getServerSocketState(QAbstractSocket::SocketState)));
    //信号槽:服务端socket出现错误
    connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(serverSocketError(QAbstractSocket::SocketError)));

    //与客户端断开某socket连接,服务端状态发生改变
    connect(socket, SIGNAL(disconnectedBeforeDeleteSignal(int)), this, SLOT(removeServerSocket(int)));
    //与客户端断开连接,输出服务器当前连接
    //connect(socket, SIGNAL(disconnectedBeforeDeleteSignal(int)), this, SLOT(getAllConnection()));	
	//与客户端连接上后,输出服务器当前连接
    //connect(socket, SIGNAL(connectedForServerSignal(int)), this, SLOT(getAllConnection()));
    //与客户端连接上后,输出服务器当前连接
    //connect(socket, SIGNAL(connectedForServerSignal(int)), this, SLOT(addServerSocket(int)));

}
开发者ID:PonyYu,项目名称:OCR_LIVE_HISTORY,代码行数:35,代码来源:TcpServer.cpp


示例10: on_connect

int FileService::on_connect(Socket *socket)
{
	TcpSocket * tcpsock = dynamic_cast<TcpSocket *> (socket);
    tcpsock->set_recv_buffer_size(1000 * 1024);

//dlog1("FileServer new connection %s %d \n", socket->remote_addr.get_ip().c_str(), socket->remote_addr.get_port());
	return FSM_END;
}
开发者ID:BotterLiu,项目名称:cnet,代码行数:8,代码来源:fileserver.cpp


示例11: broadcast

void TcpSocketServer::broadcast(const void* data, size_t size)
{
	for (Clients::iterator itr = _clients.begin(), end = _clients.end(); itr != end; ++itr)
	{
		TcpSocket* client = *itr;
		client->send(data, size);
	}
}
开发者ID:noriter,项目名称:nit,代码行数:8,代码来源:Socket.cpp


示例12: Accept

 bool Accept(TcpSocket& clientSocket) const
 {
     clientSocket.Close();
     InetAddr& clientAddr = clientSocket.Addr();
     int connFd = accept(m_Fd, (struct sockaddr*)&clientAddr.m_Addr, &clientAddr.m_AddrLen);
     clientSocket.m_Fd = connFd;
     return connFd != -1;
 }
开发者ID:,项目名称:,代码行数:8,代码来源:


示例13: on_actionCreateTcpClient_triggered

void ChooseConnectionDlg::on_actionCreateTcpClient_triggered()
{
    TcpSocket * port = sConMgr2.createTcpSocket();
    port->setName(tr("New TCP client"));
    port->setHost("localhost");
    port->setPort(80);
    this->focusNewConn(port);
}
开发者ID:onenonlycasper,项目名称:Lorris,代码行数:8,代码来源:chooseconnectiondlg.cpp


示例14: LOG

BOOL WINAPI SkylarkApp::CtrlCHandlerRoutine(__in  DWORD dwCtrlType)
{
	LOG("Ctrl+C handler");
	TheApp().quit = true;
	Cout() << "Ctrl + C\n";
	TcpSocket h;
	h.Connect("127.0.0.1", TheApp().port);
	h.Put("quit");
	return TRUE;
}
开发者ID:dreamsxin,项目名称:ultimatepp,代码行数:10,代码来源:App.cpp


示例15: Broadcast

void SkylarkApp::Quit()
{
	quit = true;
#ifdef PLATFORM_POSIX
	Broadcast(SIGTERM);
#endif
	TcpSocket s;
	s.Timeout(100);
	s.Connect("127.0.0.1", port);
}
开发者ID:dreamsxin,项目名称:ultimatepp,代码行数:10,代码来源:App.cpp


示例16: readLinesFromClientTest

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;
    }
}
开发者ID:joaotavora,项目名称:minns,代码行数:60,代码来源:TcpSocketUnit.cpp


示例17: Request

String Request(const String& r)
{
	TcpSocket s;
	if(!s.Connect(CommandLine().GetCount() ? CommandLine()[0] : "127.0.0.1", 3214)) {
		Cout() << "Unable to connect to server!\n";
		SetExitCode(1);
		return Null;
	}
	s.Put(r + '\n');
	return s.GetLine();
}
开发者ID:AbdelghaniDr,项目名称:mirror,代码行数:11,代码来源:SocketClient.cpp


示例18: sizeof

bool TcpSocketServer::update()
{
	if (!isValid())
		return false;

	sockaddr_in clientAddr = { 0 };
	socklen_t addrLen = sizeof(clientAddr);
	SOCKET accepted = ::accept(_handle, (sockaddr*)&clientAddr, &addrLen);

	if (accepted != INVALID_SOCKET)
	{
		String peerAddr = inet_ntoa(clientAddr.sin_addr);
		uint16 peerPort = clientAddr.sin_port;

		TcpSocket* client = _listener ? _listener->onAccept(this, accepted, peerAddr, peerPort) : NULL;

		if (client == NULL)
		{
			::closesocket(accepted);
			LOG(0, "++ ServerSocket: '%s: %d' refused\n", peerAddr.c_str(), peerPort);
		}
		else
		{
			LOG(0, "++ ServerSocket: '%s: %d' accepted\n", peerAddr.c_str(), peerPort);
			_clients.insert(client);
		}
	}
	else
	{
		int err = getLastError();
		if (err != ERR_WOULD_BLOCK)
			return error("Listen", err);
	}

	for (Clients::iterator itr = _clients.begin(), end = _clients.end(); itr != end; )
	{
		TcpSocket* client = *itr;
		if (!client->update())
		{
			if (_listener) _listener->onDisconnected(this, client);
			_clients.erase(itr++);
		}
		else
		{
			++itr;
		}
	}

	if (_listener) _listener->onUpdate();

	return true;
}
开发者ID:noriter,项目名称:nit,代码行数:52,代码来源:Socket.cpp


示例19: sendReceiveObjectTest

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;
    }
}
开发者ID:joaotavora,项目名称:minns,代码行数:57,代码来源:TcpSocketUnit.cpp


示例20: replyClientMessage

/**
 *函数介绍:回复客户端数据
 *输入参数:回复数据QByteArray result,套接字描述符 descriptor
 *返回值:无
 */
void TcpServer::replyClientMessage(QByteArray result,int descriptor)
{
    TcpSocket *serverSocket;
    if(descriptor!=-1)
    {
        //获得服务端套接字
        serverSocket = getServerSocket(descriptor);
        //发送数据
        if(serverSocket)
			serverSocket->sendMessage(result);
		qDebug()<<"正在回复数据。。。。。。";
    }
}
开发者ID:PonyYu,项目名称:OCR_LIVE_HISTORY,代码行数:18,代码来源:TcpServer.cpp



注:本文中的TcpSocket类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ TdfParser类代码示例发布时间:2022-05-31
下一篇:
C++ TcpSessionPtr类代码示例发布时间:2022-05-31
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap