客户端
//发送消息到服务器的槽
void Dialog::slot_sendmessage()
{
if(this->isconnetion)
{
QString user =ui->userEdit->text();
QString password=ui->password2Edit->text();
QString datedata=ui->dateEdit->text();
QString sexdata=ui->sexBox->currentText();
QString emaildata=ui->emailEdit->text();
QString phonedata=ui->phoneEdit->text();
QString sendMessage = user
+"#"+password
+"#" +sexdata
+"#" +phonedata
+"#" +emaildata
+"#" +datedata;//从单行文本框获得要发送消息
if(!sendMessage.isEmpty())
{
//发送消息到服务器
this->sendMesSocket->write(sendMessage.toLatin1());
//本地显示发送的消息
QString localDispalyMessage = tr("send to server: ") + sendMessage \
+ QDateTime::currentDateTime().toString(" yyyy-M-dd hh:mm:ss") + tr("\n");
ui->textBrowser->append(localDispalyMessage);
}
else
QMessageBox::warning(this,"错误","消息不能为空!",QMessageBox::Ok);
}
else
QMessageBox::warning(this,"错误","未连接到服务器!",QMessageBox::Ok);
ui->userEdit->clear();
}
void Dialog::slot_recvmessage()
{
//接收来自服务器的消息
QByteArray byteArray = this->sendMesSocket->readAll();
QString recvMessage = tr("recv from server: ") + byteArray + QDateTime::currentDateTime().toString(" yyyy-M-dd hh:mm:ss") + tr("\n");
ui->textBrowser->append(recvMessage);
}
服务器
void Widget::slot_recvmessage()
{
if(socket != nullptr) //与客户端连接的socket,不是nullptr,则说明有客户端存在
{
QByteArray array = socket->readAll(); //接收消息
QHostAddress clientaddr = socket->peerAddress(); //获得IP
int port =socket->peerPort(); //获得端口号
QDateTime datetime = QDateTime::currentDateTime();
QString sendMessage = tr("recv from :") + clientaddr.toString() + tr(" : ") \
+ QString::number(port) + tr(" ") + datetime.toString("yyyy-M-dd hh:mm:ss") + tr("\n");
sendMessage += array;
ui->textBrowser->append(sendMessage); //将接收到的内容加入到listwidget
}