1、需要在pro里添加network
2、qtcpserver qtcpsocket tcp客户端 tcpSocket = new QTcpSocket(this); connect(tcpSocket, SIGNAL(connected()), this, SLOT(connectedInt()));connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(disconnectedInt()));connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readMessage())); //接收到数据connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError))); 客户端连接函数 tcpSocket->abort();3、服务器端tcpSocket->connectToHost(lineEditHost->text(), lineEditPort->text().toInt());客户端读取数据
QDataStream in(tcpSocket); //这里数据已经在in里了,读取的时候数据类型一定要移植,否则会出错in.setVersion(QDataStream::Qt_4_7);if(blockSize == 0){if(tcpSocket->bytesAvailable() < (int)sizeof(quint16))return;in >> blockSize;}if(tcpSocket->bytesAvailable() < blockSize)return;in >> message;labelReceive->setText(message);
tcpServer = new QTcpServer; //建立服务器if(!tcpServer->listen(QHostAddress::LocalHost, 6666)) //绑定端口号,监听{qDebug() << tcpServer->errorString();close();}connect(tcpServer, SIGNAL(newConnection()), this, SLOT(sendMessage())); //有新连接时调用槽函数 槽函数 void Widget::sendMessage(){
static int i;QByteArray block;QDataStream out(&block, QIODevice::WriteOnly); //熟悉qdatastream的使用,另外,tcp发送数据是以QbyteArray格式来的out.setVersion(QDataStream::Qt_4_7);out << (quint16)0;out << tr("Hello guy!");out.device()->seek(0);out << (quint16)(block.size() - sizeof(quint16));QTcpSocket *clientConnection = tcpServer->nextPendingConnection(); //为新连接创建一个tcpsocketconnect(clientConnection, SIGNAL(disconnected()), clientConnection,SLOT(deleteLater()));// clientConnection->disconnectFromHost();// clientConnection->connectToHost();clientConnection->write(block); //发送数据clientConnection->disconnectFromHost(); //发完数据断开连接, 我觉得这时候对方收到断开连接的时候,应该调用tcp_close关闭连接lineEdit->setText(tr("one message has been sended!") + QString("%1").arg(i));}