在网盘的功能完善中,还有一个删除好友的操作,具体步骤如下:
目录
1、步骤如下:
A、客户端A发送删除好友(发送的信息包括双方的用户名)
B、服务器将数据库中好友信息删除,并发送删除信息给客户端A、B
C、客户端B接收信息并显示
2、代码实现:
2.1、添加删除好友按钮的槽
//删除好友
void deleteFriend();
2.2、添加定义
void Friend::deleteFriend()
{
if(NULL!=m_pFriendListWidget->currentItem()->text())
{
//通过ListWidget里获得当前的Item,再通过Item获得当前的文本
QString strFriendName = m_pFriendListWidget->currentItem()->text();
PDU *pdu =mkPDU(0);
pdu->uiMsgType=ENUM_MSG_TYPE_DELETE_FRIEND_REQUEST;
QString strSelfName = TcpClient::getinstance().loginName();
memcpy(pdu->caData,strSelfName.toStdString().c_str(),strSelfName.size());
memcpy(pdu->caData+32,strFriendName.toStdString().c_str(),strFriendName.size());
//通过socket将pdu发送给服务器
TcpClient::getinstance().getTcpSocket().write((char*)pdu,pdu->uiPDULen);
free(pdu);
pdu=NULL;
}
}
删除好友的时候,我们要先在好友列表里面选上要删除的好友,必须选上,否则不予以删除
A、获得所选择的内容
通过ListWidget里获得当前的Item,再通过Item获得当前的文本
m_pFriendListWidget->currentItem()->text();
2.3、关联删除好友的槽函数
//关联删除好友槽函数
connect(m_pDelFriendPB,SIGNAL(clicked(bool)), this, SLOT(DeleteFriend()));
2.4、添加删除好友的协议
ENUM_MSG_TYPE_DELETE_FRIEND_REQUEST, //刷新好友请求
ENUM_MSG_TYPE_DELETE_FRIEND_RESPOND, //刷新好友回复
2.5、操作服务器
A、在数据库操作类里面添加删除好友操作函数
bool handleDeleteFriend(const char *name, const char *friendname);
bool OperateDB::handleDeleteFriend(const char *name, const char *friendname)
{
if(NULL==name||NULL==friendname)
{
return false;
}
QString data = QString("delete from friend where id=(select id from usrInfo where name=\'%1\') "
"and friendId=(select id from usrInfo where name=\'%2\')").arg(name).arg(friendname);
//qDebug()<<data;
QSqlQuery query;
query.exec(data);
data = QString("delete from friend where id=(select id from usrInfo where name=\'%1\') "
"and friendId=(select id from usrInfo where name=\'%2\')").arg(friendname).arg(name);
//qDebug()<<data;
query.exec(data);
return true;
}
B、添加删除好友的请求case
case ENUM_MSG_TYPE_DELETE_FRIEND_REQUEST:
{
char caSelfName[32] = {'\0'};
char caFriendName[32] ={'\0'};
strncpy(caSelfName, pdu->caData, 32);
strncpy(caFriendName, pdu->caData+32, 32);
OperateDB::getInstance().handleDeleteFriend(caSelfName,caFriendName);
break;
}
C、删除之后给双方进行消息提示
//删除消息提示
PDU *respdu =mkPDU(0);
respdu->uiMsgType=ENUM_MSG_TYPE_DELETE_FRIEND_RESPOND;
strcpy(respdu->caData,DELETE_FRIEND_OK);
//发送
write((char*)respdu, respdu->uiPDULen);
//释放空间
free (respdu);
respdu =NULL;
//B在线就给提示,否则不给提示
//在线
MyTcpServer::getInstance().reSend(caFriendName,pdu);
2.6、收数据
//-------------------删除好友-------------
case ENUM_MSG_TYPE_DELETE_FRIEND_REQUEST:
{
//谁删除了我
char caName[32]={'\0'};
memcpy(caName,pdu->caData,32);
QMessageBox::information(this,"删除好友",QString ("%1删除了你作为他的好友").arg(caName));
break;
}
case ENUM_MSG_TYPE_DELETE_FRIEND_RESPOND:
{
QMessageBox::information(this,"删除好友","删除好友成功");
break;
}