Qt开发——TCP协议下的socket通信

来源:互联网 发布:mysql 字段命名规范 编辑:程序博客网 时间:2024/04/27 18:49

用qt写socket通信是在是太方便了。我偷懒把client和server写在一个qt控制台程序里了:

pro文件:

#-------------------------------------------------## Project created by QtCreator 2015-10-02T18:16:54##-------------------------------------------------QT       += core networkQT       -= guiTARGET = tcpCONFIG   += consoleCONFIG   -= app_bundleTEMPLATE = appSOURCES += main.cppHEADERS += server.h

server.h:

#ifndef SERVER_H#define SERVER_H#endif // SERVER_H#include <QObject>#include <QTcpServer>#include <QTcpSocket>class Server: public QObject{    Q_OBJECTprivate:    QTcpServer *server;    QTcpSocket *socket;public:    Server();    ~Server();public slots:    void getSocket();    void print();};

main.cpp:

#include <QCoreApplication>#include <server.h>Server::Server(){    server = new QTcpServer();    server->listen(QHostAddress::Any, 12345);    QObject::connect(server, SIGNAL(newConnection()), this, SLOT(getSocket()));}void Server::getSocket(){    socket = server->nextPendingConnection();    QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(print()));}void Server::print(){    QByteArray content= socket->readAll();    qDebug() << "This is message transmitted with Tcp:";    qDebug() << content;    qDebug() << "end.";}Server::~Server(){    delete server;}int main(int argc, char *argv[]){    QCoreApplication a(argc, argv);    Server x;    QTcpSocket client;    client.connectToHost("127.0.0.1", 12345);    client.write("haha");    return a.exec();}

运行结果如下:



0 0
原创粉丝点击