源码连接http://download.csdn.net/detail/qq_28637193/9615451
pro中需要加入
QT += network
头文件
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include<QTcpSocket> class QTcpServer; namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private: Ui::MainWindow *ui; QTcpServer *tcpServer; QTcpSocket *tcpServerConnection; quint16 blockSize; QString message; private slots: void sendMessage(); void acceptConnection(); void readMessage(); }; #endif // MAINWINDOW_H
实现文件cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QtNetwork> #include<QNetworkAccessManager> #include<QNetworkReply> #include<QNetworkRequest> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); tcpServer=new QTcpServer(this); // 使用了IPv4的本地主机地址,等价于QHostAddress("127.0.0.1") if (!tcpServer->listen(QHostAddress::Any, 6666)) { qDebug() << tcpServer->errorString(); close(); } connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(sendMessage())); connect(tcpServer,SIGNAL(newConnection()),this,SLOT(acceptConnection())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::sendMessage() { // 用于暂存我们要发送的数据 QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); // 设置数据流的版本,客户端和服务器端使用的版本要相同 out.setVersion(QDataStream::Qt_4_6); out << (quint16)0; out << tr("hello TCP!!!"); out.device()->seek(0); out << (quint16)(block.size() - sizeof(quint16)); // 获取已经建立的连接的套接zi // 发送数据成功后,显示提示 tcpServerConnection->write(block); ui->label->setText("send message successful!!!"); } void MainWindow::acceptConnection() { tcpServerConnection = tcpServer->nextPendingConnection(); connect(tcpServerConnection, SIGNAL(readyRead()), this, SLOT(readMessage())); connect( tcpServerConnection,SIGNAL(disconnected()), tcpServerConnection, SLOT(deleteLater())); connect(tcpServerConnection, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError))); ui->label->setText(tr("接受连接")); // 关闭服务器,不再进行监听 // tcpServer->close(); } void MainWindow::readMessage() { blockSize=0; qDebug()<<4; QDataStream in(tcpServerConnection); // 设置数据流版本,这里要和服务器端相同 in.setVersion(QDataStream::Qt_4_6); // 如果是刚开始接收数据 if (blockSize == 0) { //判断接收的数据是否大于两字节,也就是文件的大小信息所占的空间 //如果是则保存到blockSize变量中,否则直接返回,继续接收数据 if(tcpServerConnection->bytesAvailable() < (int)sizeof(quint16)) return; //bytesAvailable()返回字节数 in >> blockSize; } // 如果没有得到全部的数据,则返回,继续接收数据 if(tcpServerConnection->bytesAvailable() < blockSize) return; // 将接收到的数据存放到变量中 in >> message; // 显示接收到的数据 blockSize=0; }