[Qt] QLocalSocket实现简单的CS连接

目录

1.客户端

2.服务器

3.连接测试


利用Qt的QLocalSocket机制实现简单的服务器客户端连接。 

1.客户端

 client.h

#ifndef CLIENT_H
#define CLIENT_H

#include 
#include 
#include 

class CClient : public QObject
{
    Q_OBJECT

public:
    CClient() : m_socket(NULL)
    {
        m_socket = new QLocalSocket();

        connect(m_socket, SIGNAL(connected()), SLOT(socketConnectedHandler()));
        connect(m_socket, SIGNAL(disconnected()), SLOT(socketDisConnectedHandler()));
        connect(m_socket, SIGNAL(error(QLocalSocket::LocalSocketError)),                                                                                              
                    SLOT(socketErrorHandler(QLocalSocket::LocalSocketError)));
    }

    ~CClient()
    {
        m_socket->disconnectFromServer();
        delete m_socket;
    }

public:
    void ConnectToServer(const QString &strServerName)
    {
        // serverNewConnectionHandler 成员方法将被调用
        m_socket->connectToServer(strServerName);
        if (m_socket->waitForConnected())
        {
            // TODO:
        }
    }

    void sendMessage(const QString &msg)
    {
        m_socket->write(msg.toStdString().c_str());
        m_socket->flush();

        if (!m_socket->bytesAvailable())
            m_socket->waitForReadyRead();

        QTextStream stream(m_socket);
        QString respond = stream.readAll();
        qDebug() << "Read Data From Server:" << respond;
    }

private slots:
    void socketConnectedHandler()
    {
        qDebug() << "connected.";
    }


    void socketDisConnectedHandler()
    {
        qDebug() << "disconnected.";
    }

    void socketErrorHandler(QLocalSocket::LocalSocketError error)
    {
        qWarning() << error;
    }

private:
    QLocalSocket *m_socket;

};

#endif // CLIENT_H

main.cpp

#include "client.h"
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    CClient client;
    client.ConnectToServer("ServerName");

    client.sendMessage("Hellow Server");

    return a.exec();
}

2.服务器

  server.h

#ifndef SERVER_H
#define SERVER_H

#include 
#include 
#include 
#include 

class CServer : public QObject
{
    Q_OBJECT

public:
    CServer() : m_server(NULL)
    {
        m_server = new QLocalServer;
        connect(m_server, SIGNAL(newConnection()), SLOT(serverNewConnectionHandler()));
    }

    ~CServer()
    {
        m_server->close();
        delete m_server;
    }

    void RunServer()
    {
        qDebug() << "Run Server ok";

        QLocalServer::removeServer("ServerName");
        bool ok = m_server->listen("ServerName");
        if (!ok)
        {
            // TODO:
        }
    }

private slots:
    void serverNewConnectionHandler()
    {
        qDebug() << "New Connection";
        qDebug() << "listen: " << m_server->serverName();

        QLocalSocket* socket = m_server->nextPendingConnection();
        connect(socket, SIGNAL(readyRead()), this, SLOT(socketReadyReadHandler()));
        connect(socket, SIGNAL(disconnected()), socket, SLOT(deleteLater()));
    }

    void socketReadyReadHandler()
    {
        QLocalSocket* socket = static_cast(sender());
        if (socket)
        {
            QTextStream stream(socket);
            qDebug() << "Read Data From Client:" << stream.readAll();

            QString response = "Hello Client";
            socket->write(response.toUtf8());
            socket->flush();
        }
    }

private:
    //判断该服务器是否在运行
    bool isServerRun(const QString &servername)
    {
        QLocalSocket socket;
        socket.connectToServer(servername);
        if(socket.waitForConnected(1000))
        {
            socket.disconnectFromServer();
            socket.close();
            return true;
        }
        return false;
    }

private:
    QLocalServer *m_server;

};

#endif // SERVER_H

main.cpp

#include "server.h"
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    CServer server;
    server.RunServer();
//    server.initServer(QString("ServerName"));

    return a.exec();
}

3.连接测试

                                                           

                                                           

你可能感兴趣的:(QT)