Qt服务器的搭建

来源:互联网 发布:淘宝名叫什么好 编辑:程序博客网 时间:2024/05/29 12:32
项目的.pro文件添加:

QT+= network

项目的.h文件添加
#include <QAbstractSocket>
#include <QtNetwork>

char a[20];

    QTcpServer *tcpServer=new QTcpServer(this);//用于创建服务器连接
    QTcpSocket *clientConnection;//用于处理连接成功后和客户端的数据处理
项目.cpp文件中添加
    //服务器设置
    tcpServer=new QTcpServer(this);
    //使用了IPv4的本地主机地址,等价于QHostAddress("127,0,0,1")
    if(!tcpServer->listen(QHostAddress("127.0.0.1"),8899))
    {
        qDebug()<<tcpServer->errorString();
        close();
    }
    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(sendMessage()));
void Widget::sendMessage()//记得去.h头文件声明槽函数
{
    clientConnection =tcpServer->nextPendingConnection();//当前的这个网络连接交给我的QTcpSocket对象,从这里开始往后所有网络传输的工作都使用它来完成了,就是说我的QTcpServer类的对象,只完成一个监听的功能就算是光荣完成任务了,之后的事情就不需要再管了。如果只需要做一次连接,甚至可以将其close掉。
    connect(clientConnection,SIGNAL(readyRead()),this,SLOT(readMessage()));
}
void Widget::readMessage()//记得去.h头文件声明槽函数
clientConnection->read(a,8);接收数据

0 0
原创粉丝点击