我正在尝试使用Qt和C ++为学校网络项目构建一个基本的IM客户端。我是Qt的新手,只有一个学期的C ++(但一般有4个以上的编程,2个C,1个C ++和* Nix环境中的脚本之一),但感觉Qt对我来说是最好的考虑它拥有的文档以及它具有的网络和GUI支持。我正在尝试获取服务器和客户端的基本功能。我在服务器和客户端之间设计了一个简单的消息传递系统来做一些事情,例如向客户端发送消息,注册为在线用户,以及离线,但在我开始从事更高级别的项目之前,我我想确保我可以依赖这个基础消息传递来正常行事。我遇到了麻烦。截至目前,我得到两个连接,服务器听到客户端,正确行动并发回响应消息。然后客户端响应确认并发送用户名。服务器注册用户名并返回另一个确认。我的问题是,当服务器认为它发送了ack时,客户端永远不会得到它。
这是服务器的readyRead()插槽(仅通过我测试的区域,我测试了其他命令,但我还没有开始测试)。
void mythread::readyRead()
{ //this will change
QMutex lock;
int flag=0;
Data dData;
QLinkedList<User>::iterator Uit;
QString::iterator it;
User temp;
QByteArray stuff = socket->readAll();
qDebug() << stuff;
QString stuffText;
stuffText.clear();
qDebug() << socketDescriptor << "Data in: " << stuff;
//connect new client REG command
if (stuff == "REG\n") //client would like to register. next message should be username
{//need to add check to see if user exists
socket->write("ACK"); //this is a hard ack that tells the client that it may write to the socket and be heard by the server.
stuff.clear(); //verify that buffer is cleared.
socket->waitForReadyRead();
stuff=socket->readAll();//should have username followed by \n
stuffText = stuff; //move it to a string so that I can manually remove the \n and then add it to the users list.
stuffText.remove('\n'); //hopefully removes the \n
//now to add to the user list, completing the register process.
temp.setName(stuffText);
temp.setDescriptor(this->socketDescriptor);//temp user configured. time to add
lock.lock();
users.append(temp);
lock.unlock();
//clean up
stuff.clear();
stuffText.clear();
temp.clear();
stuff="ACK";
int ans;
socket->flush();
ans = socket->write("ACK");
if(ans==-1)
{
qDebug()<< ans << "Didn't work."; //client can send data again.
}
else qDebug()<< ans <<"wrote the ack."; //client has been added to the list. waiting for other data.
}
这是客户方。
void socket::Connect()
{
Socket1 = new QTcpSocket;
QByteArray stuff;
Socket1->connectToHost("localhost",8060);
if(Socket1->waitForConnected(3000))
{
qDebug() << "Connected";
Socket1->write("REG\n");
Socket1->waitForBytesWritten(1000); //big times for testing
Socket1->waitForReadyRead(3000);
qDebug() << "Reading:" << Socket1->bytesAvailable();
stuff = Socket1->readAll();
qDebug() << stuff;
if(stuff=="ACK")
{
Socket1->write("Sean\n");
Socket1->waitForReadyRead(3000);
if(Socket1->bytesAvailable())
{
stuff = "this"; //to test if reading is changing value at all.
stuff = Socket1->readAll();
qDebug() << stuff;
if(stuff=="ACK")
{
qDebug() << "got second ack"; //good
}
}
else qDebug() << "Didn't get anything.";
}
else Socket1->close();
Socket1->close();
}
else
{
qDebug() <<"Not connected!";
}
}
我知道这里有很多代码,如果我知道如何缩小代码,我会的。我现在一直在努力解决这个问题大约3个晚上,这真的让人很沮丧。我甚至已经做了很多事情,比如禁用防火墙,运行服务器一台计算机,在另一台计算机上运行客户端。
对于一些额外的信息,我有wireshark捕获帮助。
从服务器(服务器是.116)。 http://i47.tinypic.com/2u9k3t1.jpg
来自客户端(客户端是.100)http://i49.tinypic.com/2yv9nar.jpg
我看不出彼此有什么不同。他们似乎按正确的顺序拥有相同的数据包。
感谢您的帮助。