客户端程序,点击按钮调用slotEnter,连接服务器:
void TcpClient::slotEnter()
{
if(!status)
{
QString ip=LineEditServerIP->text();
if(!serverIP->setAddress(ip))
{
QMessageBox::information(this,tr("error"),tr("server ip address error!"));
return;
}
if(LineEditUser->text()=="")
{
QMessageBox::information(this,tr("error"),tr("User name error!"));
return ;
}
userName=LineEditUser->text();
//tcpSocket = new QTcpSocket(this);//在这里new就没有问题
connect(tcpSocket,SIGNAL(connected()),this,SLOT(slotConnected()));
connect(tcpSocket,SIGNAL(disconnected()),this,SLOT(slotDisconnected()));
connect(tcpSocket, SIGNAL(readyRead()),this, SLOT(dataReceived()));
tcpSocket->connectToHost ( *serverIP, port);
status=true;
}
else
{
int length = 0;
QString msg=userName+tr(":Leave Chat Room");
if((length=tcpSocket->write(msg.toLatin1(),msg.length()))!=msg.length())
{
return ;
}
tcpSocket->disconnectFromHost();
status=false;
}
}
void TcpClient::slotConnected()
{
int length = 0;
PushButtonSend->setEnabled( true );
PushButtonEnter->setText(tr("Leave"));
QString msg=userName+tr(":Enter Chat Room");
if((length=tcpSocket->write(msg.toLatin1(),msg.length()))!=msg.length())
{
return ;
}
}
void TcpClient::slotDisconnected()
{
PushButtonSend->setEnabled( false );
PushButtonEnter->setText(tr("Enter"));
}
本来这样考虑,每次点击,连接服务器都要new QTcpSocket似乎不太好,就在TcpClient构造函数事先new好,后面调用connectToHost和 disconnectFromHost即可。但是经测试,如果这样做,slotConnected()会调用两次,也就是说connected()信号会发射两次。(什么原因?)三个connect要放到构造函数中去
忘记信号和槽还连着:
connect(tcpSocket,SIGNAL(connected()),this,SLOT(slotConnected()));
connect(tcpSocket,SIGNAL(disconnected()),this,SLOT(slotDisconnected()));
connect(tcpSocket, SIGNAL(readyRead()),this, SLOT(dataReceived()));
阅读(6825) | 评论(0) | 转发(0) |