Chinaunix首页 | 论坛 | 博客
  • 博客访问: 303578
  • 博文数量: 45
  • 博客积分: 1429
  • 博客等级: 上尉
  • 技术积分: 422
  • 用 户 组: 普通用户
  • 注册时间: 2010-01-19 09:12
文章分类

全部博文(45)

文章存档

2021年(1)

2020年(1)

2019年(1)

2016年(4)

2015年(3)

2011年(4)

2010年(31)

我的朋友

分类: LINUX

2010-07-06 23:57:29

客户端程序,点击按钮调用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()));
 
阅读(6759) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~