版权声明:本文为博主原创文章,未经博主允许不得转载。
最近想用Qt做一个简单的聊天室,用到了TCP传输,在此整理一下有关TCP传输的东西。(只是简单的实现数据传送,对于一些出错情况没有考虑,适于新手学习,本人也是个菜鸟)
在Qt中有QTcpsockey和QTcpserver两个类,QTcpserver主要是用来在服务器端监听客户端的连接请求,QTcpsocket用来传输数据。
服务器的建立:在.h文件中添加
QTcpSocket *m_tcpsocket;
QTcpServer *m_tcpserver;
.cpp中添加:
m_tcpserver = new QTcpServer(this);
m_tcpsocket = new QTcpSocket(this);
m_tcpserver->listen(QHostAddress::Any,6666);//监听的端口号
connect(m_tcpserver,SIGNAL(newConnection()),
this,SLOT(newConnect()));
void Widget::newConnect()
{
m_tcpsocket = m_tcpserver->nextPendingConnection();//设置监听
connect(m_tcpsocket,SIGNAL(readyRead()),
this,SLOT(readMessage())); //服务器接收客户端的消息
connect(m_tcpsocket,SIGNAL(disconnected()),
m_tcpsocket,SLOT(deleteLater()));
}
服务器端发送数据:
void Widget::readMessage()
{
QDataStream in(m_tcpsocket);
in.setVersion (QDataStream::Qt_5_4);
in >> message;
qDebug() << "ser message" << message;
ui->textBrowser->setText(tr("reveived client message: '%1'").arg(message));
}服务器端接受数据:
void Widget::sendMessage()
{
QString string = ui->lineEdit->text();
QByteArray message;
QDataStream out(&message,QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_4);
out< m_tcpsocket->write(message);}
客户端的建立在.h中:QTcpSocket *m_tcpsocket;在.cpp中void Widget::tcpServerConnect(){m_tcpsocket = new QTcpSocket(this);m_tcpsocket->abort();m_tcpsocket->connectToHost(QHostAddress::LocalHost,6666);//设置客户端的端口号connect(m_tcpsocket,SIGNAL(readyRead()),this,SLOT(readMessage()));//用于接受数据// m_tcpsocket->connectToHost("localhost",6666);}发送数据:void Widget::sendMessage(){QString string = ui->lineEdit->text();QByteArray message;QDataStream out(&message,QIODevice::WriteOnly);out.setVersion(QDataStream::Qt_5_4);out< m_tcpsocket->write(message);}接收数据void Widget::readMessage(){QDataStream in(m_tcpsocket);in.setVersion(QDataStream::Qt_5_4);QString greeting;in >> greeting;ui->lineEdit_2->setText(tr("received server message '%1'").arg(greeting));}希望大家共同学习,有错误积极指出。完整代码下载地址:http://download.csdn.net/download/qq_33425353/9573296