本文整理汇总了C++中QTcpSocket::state方法的典型用法代码示例。如果您正苦于以下问题:C++ QTcpSocket::state方法的具体用法?C++ QTcpSocket::state怎么用?C++ QTcpSocket::state使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QTcpSocket
的用法示例。
在下文中一共展示了QTcpSocket::state方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: deal_next_request
void brain_stroke_server::deal_next_request(){
puts("deal next");
//get next request
deque_mutex.lock();
if(request_list.size() != 0){
puts("has next");
QTcpSocket * client = request_list.front();
request_list.pop_front();
deque_mutex.unlock();
//ignore closing socket
if(client->state() == QTcpSocket::UnconnectedState || client->state() == QTcpSocket::ClosingState){
client->close();
QLOG_DEBUG() << "close client" << client;
std::cout << "close client:" << client->peerAddress().toString().toStdString() << std::endl;
//search next from request_list
deal_next_request();
return;
}
tcp_deal * tcp_deal_thread = new tcp_deal();
tcp_deal_thread -> set_socket(client);
connect(tcp_deal_thread, SIGNAL(finished()), this, SLOT(deal_next_request()));
connect(tcp_deal_thread, SIGNAL(finished()), tcp_deal_thread, SLOT(deleteLater()));
tcp_deal_thread -> start();
return;
}
deque_mutex.unlock();
QMutexLocker calculate_flag_mutex_locker(&calculate_flag_mutex);
//no calculating now
calculate_flag = false;
return;
}
示例2: SendData
bool Server::SendData(QHostAddress ip_to, QString message)
{
bool result = false;
QTcpSocket* tcpSocket = sockets->value(ip_to.toIPv4Address(), 0);
if (tcpSocket && tcpSocket->state()==QAbstractSocket::ConnectedState && tcpSocket->isWritable()) {
emit write_message(tr("Sending data (size=%1) to %2. Content: \"%3\"").arg(message.length()).arg(ip_to.toString()).arg(message));
tcpSocket->write(message.toUtf8());
result = tcpSocket->waitForBytesWritten();
} else {
tcpSocket = new QTcpSocket();
tcpSocket->connectToHost(ip_to, remote_port, QIODevice::ReadWrite);
tcpSocket->waitForConnected(5000);
if (tcpSocket->state()==QAbstractSocket::ConnectedState) {
emit write_message(tr("Sending data (size=%1) from new socket to %2. Content: \"%3\"").arg(message.length()).arg(ip_to.toString()).arg(message));
tcpSocket->write(message.toUtf8());
result = tcpSocket->waitForBytesWritten(5000);
} else {
emit error(tr("Client \"%1\" not found").arg(ip_to.toString()));
}
tcpSocket->abort();
delete tcpSocket;
}
return result;
}
示例3: streamLoop
void streamLoop(qintptr socketDesc, QQueue<QByteArray> &queue, bool& streaming) {
QTcpSocket* socket = new QTcpSocket();
// TCP_NODELAY + disable Nagle's algorithm
socket->setSocketOption(QAbstractSocket::LowDelayOption, QVariant::fromValue(1));
// Internetwork control
socket->setSocketOption(QAbstractSocket::TypeOfServiceOption, QVariant::fromValue(192));
socket->setSocketDescriptor(socketDesc);
socket->readAll();
QByteArray ContentType = ("HTTP/1.1 200 OK\r\n" \
"Server: test\r\n" \
"Cache-Control: no-cache\r\n" \
"Cache-Control: private\r\n" \
"Connection: close\r\n"\
"Pragma: no-cache\r\n"\
"Content-Type: multipart/x-mixed-replace; boundary=--boundary\r\n\r\n");
socket->write(ContentType);
while((socket->state() != QAbstractSocket::ClosingState ||
socket->state() != QAbstractSocket::UnconnectedState) &&
socket->state() == QAbstractSocket::ConnectedState &&
streaming) {
if(queue.empty()) { // no new frame available
continue;
}
// make sure that the queue doesn't grow too big or
// the OOM killer will kick in
if(queue.length() > 20) {
queue.clear();
continue;
}
QByteArray boundary = ("--boundary\r\n" \
"Content-Type: image/jpeg\r\n" \
"Content-Length: ");
QByteArray img = queue.dequeue();
boundary.append(QString::number(img.length()));
boundary.append("\r\n\r\n");
socket->write(boundary);
socket->waitForBytesWritten();
boundary.clear();
socket->write(img);
socket->waitForBytesWritten();
img.clear();
}
socket->flush();
socket->abort();
socket->deleteLater();
streaming = false;
queue.clear();
return;
}
示例4: AddNewClient
void SharedDaemon::AddNewClient(const std::string &host, const stringVector &args, void *cbdata)
{
/// Send appropriate message for TCP or WebConnection
void** data = (void**)cbdata;
ConnectionType typeOfConnection = *((ConnectionType*)(data[0]));
QAbstractSocket* socket = static_cast<QAbstractSocket*>(data[1]);
ViewerState* viewerState = static_cast<ViewerState*>(data[2]);
JSONNode node;
QString hostname = typeOfConnection == TcpConnection ? socket->localAddress().toString():
dynamic_cast<QWsSocket*>(socket)->internalSocket()->localAddress().toString();
if(hostMap.contains(hostname)) hostname = hostMap[hostname];
node["host"] = hostname.toStdString(); //host
node["port"] = args[7]; //port
node["version"] = args[2]; //version
node["securityKey"] = args[9]; //key
node["numStates"] = viewerState->GetNumStateObjects(); //number of states
JSONNode::JSONArray rpc_array = JSONNode::JSONArray();
for(size_t i = 0; i < ViewerRPC::MaxRPC; ++i) {
rpc_array.push_back(ViewerRPC::ViewerRPCType_ToString((ViewerRPC::ViewerRPCType)i));
}
node["rpc_array"] = rpc_array;
if(typeOfConnection == TcpConnection)
{
QTcpSocket *tsocket = dynamic_cast<QTcpSocket*>(socket);
std::string message = node.ToString();
tsocket->write(message.c_str(),message.length());
if(tsocket->state() != QAbstractSocket::UnconnectedState)
tsocket->waitForBytesWritten();
tsocket->disconnectFromHost();
if(tsocket->state() != QAbstractSocket::UnconnectedState)
tsocket->waitForDisconnected();
//HKTODO: Do not delete connection (test fix for ORNL machines)
//tsocket->deleteLater();
}
else
{
QWsSocket *wsocket = dynamic_cast<QWsSocket*>(socket);
wsocket->write(QString(node.ToString().c_str()));
wsocket->flush();
if(wsocket->internalSocket()->state() != QAbstractSocket::UnconnectedState)
wsocket->internalSocket()->waitForBytesWritten();
wsocket->close("");
wsocket->internalSocket()->disconnectFromHost();
if(wsocket->internalSocket()->state() != QAbstractSocket::UnconnectedState)
wsocket->internalSocket()->waitForDisconnected();
wsocket->deleteLater();
}
}
示例5: run
void TcpEchoServerSession::run()
{
LOG_INFO("Beginning of TcpEchoServerSession::run");
QTcpSocket socket;
if( !socket.setSocketDescriptor(m_socketDescriptor))
{
LOG_ERROR("Cannot set socket descriptor");
}
while( true )
{
// Receive request
qint16 fillSize;
qint16 echoSize;
while( socket.bytesAvailable() < 4 )
{
if( !socket.waitForReadyRead(-1)) // Intervals may vary
{
break;
}
}
if( socket.state() == QAbstractSocket::UnconnectedState )
{
break; // Connection closed by client
}
QDataStream in(&socket);
in >> fillSize >> echoSize;
// Receive filled bytes in the request
while( socket.bytesAvailable() < fillSize )
{
if( !socket.waitForReadyRead(3 * 1000))
{
LOG_INFO("TcpEcho session timed out");
return;
}
}
socket.read(fillSize);
// Send data
QByteArray block(echoSize, 0);
socket.write(block);
socket.waitForBytesWritten(-1);
if( socket.state() == QAbstractSocket::UnconnectedState )
{
break;
}
//LOG_DEBUG("TcpEchoSession sent an echo of %d bytes", (int)echoSize);
}
socket.close();
LOG_INFO("End of TcpEchoServerSession::run");
}
示例6: run
void ConnectionThread::run()
{
Debug() << "Thread started.";
QTcpSocket sock;
socketNoNagle(sockdescr);
if (!sock.setSocketDescriptor(sockdescr)) {
Error() << sock.errorString();
return;
}
QString remoteHostPort = sock.peerAddress().toString() + ":" + QString::number(sock.peerPort());
Log() << "Connection from peer " << remoteHostPort;
QString line;
forever {
if (sock.canReadLine() || sock.waitForReadyRead()) {
line = sock.readLine().trimmed();
while (StimApp::instance()->busy()) {
// special case case, stimapp is busy so keep polling with 1s intervals
Debug() << "StimApp busy, cannot process command right now.. trying again in 1 second";
sleep(1); // keep sleeping 1 second until the stimapp is no longer busy .. this keeps us from getting given commands while we are still initializing
}
// normal case case, stimapp not busy, proceed normally
QString resp;
resp = processLine(sock, line);
if (sock.state() != QAbstractSocket::ConnectedState) {
Debug() << "processLine() closed connection";
break;
}
if (!resp.isNull()) {
if (resp.length()) {
Debug() << "Sending: " << resp;
if (!resp.endsWith("\n")) resp += "\n";
QByteArray data(resp.toUtf8());
int len = sock.write(data);
if (len != data.length()) {
Debug() << "Sent " << len << " bytes but expected to send " << data.length() << " bytes!";
}
}
Debug() << "Sending: OK";
sock.write("OK\n");
} else {
Debug() << "Sending: ERROR";
sock.write("ERROR\n");
}
} else {
if (sock.error() != QAbstractSocket::SocketTimeoutError
|| sock.state() != QAbstractSocket::ConnectedState) {
Debug() << "Socket error: " << sock.error() << " Socket state: " << sock.state();
break;
}
}
}
Log() << "Connection ended (peer: " << remoteHostPort << ")";
Debug() << "Thread exiting.";
}
示例7: processTerminated
void DesignerExternalEditor::processTerminated(const QString &binary)
{
const ProcessCache::iterator it = m_processCache.find(binary);
if (it == m_processCache.end())
return;
// Make sure socket is closed and cleaned, remove from cache
QTcpSocket *socket = it.value();
m_processCache.erase(it); // Note that closing will cause the slot to be retriggered
if (debug)
qDebug() << Q_FUNC_INFO << '\n' << binary << socket->state();
if (socket->state() == QAbstractSocket::ConnectedState)
socket->close();
socket->deleteLater();
}
示例8: slotConnectionEnded
void NetworkServer::slotConnectionEnded()
{
for(int i=0; i < mTcpSockets.size(); i++)
{
QTcpSocket* socket = mTcpSockets.at(i);
if(socket->state() == QAbstractSocket::ClosingState || socket->state() == QAbstractSocket::UnconnectedState)
{
qDebug() << "NetworkServer::slotConnectionEnded(): connection from" << socket->peerAddress() << socket->peerPort() << "closed, removing socket.";
socket->disconnect();
socket->deleteLater();
mTcpSockets.removeAt(i);
}
}
}
示例9: connected
void MrimConnection::connected()
{
QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
Q_ASSERT(socket);
SystemIntegration::keepAlive(socket);
bool connected = false;
switch (socket->state())
{
case QAbstractSocket::ConnectedState:
connected = true;
break;
default:
break;
}
QString address = Utils::toHostPortPair(socket->peerAddress(),socket->peerPort());
if (!connected)
{
debug()<<"Connection to server"<<qPrintable(address)<<"failed! :(";
return;
}
else
{
debug()<<"Connected to server"<<qPrintable(address);
if (socket == p->IMSocket()) //temp
{
sendGreetings();
}
}
}
示例10: run
void ClientThread::run()
{
QTcpSocket tcpSocket;
if (!tcpSocket.setSocketDescriptor(m_socketDescriptor)) {
qWarning() << ":(((";
emit error(tcpSocket.error());
return;
}
m_running = true;
QString command, response;
// Send greetings
tcpSocket.write("OK MPD 0.12.2\n");
while (m_running && (tcpSocket.state() == QAbstractSocket::ConnectedState)) {
m_running = tcpSocket.waitForReadyRead(); // Wait for command,
// if none is received until timeout
// (default 30 seconds, stop running).
command = QString(tcpSocket.readLine()).trimmed();
qDebug() << command;
tcpSocket.write(parseCommand(command).toLocal8Bit());
}
tcpSocket.disconnectFromHost();
}
示例11: recieveConnection
void Server::recieveConnection()
{
QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()));
QString client_ip = clientConnection->peerAddress().toString();
quint32 client_ip_int = clientConnection->peerAddress().toIPv4Address();
emit write_message(tr("New connection from IP: %1").arg(client_ip));
if (sockets->contains(client_ip_int)) {
QTcpSocket *oldClientConnection = (QTcpSocket*) sockets->value(client_ip_int);
if (oldClientConnection && oldClientConnection->state() != QAbstractSocket::UnconnectedState) {
oldClientConnection->disconnectFromHost();
}
sockets->remove(client_ip_int);
}
sockets->insert(client_ip_int, clientConnection);
connect(clientConnection, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
connect(clientConnection, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
connect(clientConnection, SIGNAL(readyRead()), this, SLOT(recieveData()));
connect(clientConnection, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));
}
示例12: os
void HttpServer :: readClient()
{
if (disabled) return;
QTcpSocket *socket = (QTcpSocket*)sender();
if( socket->canReadLine()) {
QString request = socket->readLine();
QStringList tokens = request.split(QRegExp("[ \r\n][ \r\n]*"));
if( tokens[0] == "GET") {
d->engine.globalObject().setProperty("token", tokens[1]);
QScriptValue reply = d->engine.evaluate("reply(token)");
QTextStream os(socket);
os.setAutoDetectUnicode(true);
os << reply.toString().toUtf8();
socket->close();
QtServiceBase::instance()->logMessage("Wrote index.html");
if(socket->state() == QTcpSocket::UnconnectedState) {
delete socket;
QtServiceBase::instance()->logMessage("Conncetion closed");
}
}
}
}
示例13: run
void QServerThread::run()
{
QTcpSocket qsocket;
if( qsocket.setSocketDescriptor( sd) == false)
{
AFERROR("QThreadServer::run: Can't set socket descriptor.\n");
return;
}
af::Msg* msg = new af::Msg;
if( afqt::recvMessage( &qsocket, msg))
{
if( recvMessage_handler_ptr == NULL )
{
emit newmsg( msg);
}
else
{
if( recvMessage_handler_ptr( &qsocket, msg) == false)
{
emit newmsg( msg);
}
}
}
qsocket.disconnectFromHost();
if( qsocket.state() != QAbstractSocket::UnconnectedState ) qsocket.waitForDisconnected();
}
示例14: readClient
void HttpDaemon::readClient()
{
QTcpSocket* socket = (QTcpSocket*)sender();
if (socket->canReadLine())
{
QTextStream os(socket);
os.setAutoDetectUnicode(true);
os << "HTTP/1.0 200 Ok\r\n"
"Content-Type: text/html; charset=\"utf-8\"\r\n"
"\r\n";
QStringList tokens = QString(socket->readLine()).split(QRegExp("[ \r\n][ \r\n]*"));
QRegExp pathPattern("^/websocket\\.(html|js)$");
if (pathPattern.exactMatch(tokens[1]))
{
QFile file (":" + pathPattern.capturedTexts()[0]);
file.open(QFile::ReadOnly);
os << file.readAll()
<< "\n\n";
}
else
{
os << "<h1>Nothing to see here</h1>\n\n";
}
socket->close();
if (socket->state() == QTcpSocket::UnconnectedState)
delete socket;
}
}
示例15: test_send
void TCPConnectionManagerTest::test_send()
{
// Use Case:
// client requests a connection
// expect client to be registered for any data
StreamDataRequest req;
DataSpec require;
require.addStreamData("testData");
req.addDataOption(require);
QTcpSocket* client = _createClient();
_sendRequest( client, req );
QCoreApplication::processEvents();
CPPUNIT_ASSERT_EQUAL( 1, _server->clientsForStream("testData") );
TestDataBlob blob;
blob.setData("sometestData");
_server->send("testData",&blob);
sleep(1);
CPPUNIT_ASSERT( client->state() == QAbstractSocket::ConnectedState );
boost::shared_ptr<ServerResponse> r = _clientProtocol->receive(*client);
CPPUNIT_ASSERT( r->type() == ServerResponse::Blob );
DataBlobResponse* res = static_cast<DataBlobResponse*>(r.get());
CPPUNIT_ASSERT( res->dataName() == "testData" );
CPPUNIT_ASSERT( res->blobClass() == "TestDataBlob" );
TestDataBlob recvBlob;
recvBlob.deserialise(*client, res->byteOrder());
CPPUNIT_ASSERT(recvBlob == blob);
}