qt c语言socket,c – Qt双向客户端服务器使用QTcpSocket和QTcpServer
默認情況下,QTcpSocket是異步的,因此當您調(diào)用connectToHost并在相同的上下文中寫入時,將不會發(fā)送,因為套接字未連接.你應該改變你的“客戶端”代碼:
void TopLevelComms::connect(){
tcpSocket->connectToHost(hostAddress,QIODevice::ReadWrite);
if(tcpSocket->waitForConnected()) // putting 1 as parameter isn't reasonable,using default 3000ms value
{
QString string = "Hello";
QByteArray array;
array.append(string);
qDebug()<write(array);
}
else
{
qDebug() << "couldn't connect";
}
}
注意:您也沒有檢查是否能夠聽
void Comms::attemptConnection(){
connect(server,SLOT(connectionAccepted()));
//socket = server->nextPendingConnection();
if(server->listen(hostAddress,hostPort))
{
qDebug() << "Server listening";
}
else
{
qDebug() << "Couldn't listen to port" << server->serverPort() << ":" << server->errorString();
}
//receivedData = socket->readAll();
}
最后一件事.請注意,QTcpServer :: nextPendingConnection()返回QTcpSocket,因此,不要采用新的連接,您可以使用nextPendingConnection創(chuàng)建新的QTcpSocket作為父
void Comms::connectionAccepted(){
qDebug()<
// WRONG! it will use QTcpSocket::QTcpSocket(QObject * parent)
//socket = new QTcpSocket(server->nextPendingConnection());
// use simple asign
socket = server->nextPendingConnection();
// move reading to slot
connect(socket,SIGNAL(readyRead()),SLOT(readSocket()));
}
現(xiàn)在我們將把閱讀移到單獨的插槽
void Comms::readSocket()
{
// note that dynamic size array is incompatible with some compilers
// we will use Qt data structure for that
//char* rec = new char[socket->readBufferSize()];
qDebug()<readBufferSize();
// note that QByteArray can be casted to char * and const char *
QByteArray data = socket->readAll();
}
我必須承認,這樣的小代碼示例是很多錯誤.您需要了解有關TCP / IP連接的一些知識.那些是流,并且沒有一個保證,整個數(shù)據(jù)塊將一次給你
總結(jié)
以上是生活随笔為你收集整理的qt c语言socket,c – Qt双向客户端服务器使用QTcpSocket和QTcpServer的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C语言libiconv编程,libico
- 下一篇: oracle 10g ocp 047解析