Qt Socket 通讯示例2

服务端代码

// MyTcpSocket.h

#ifndef MYTCPSOCKET_H
#define MYTCPSOCKET_H

#include <QTcpSocket>
#include <QDebug>

#pragma execution_character_set("utf-8")

class MyTcpSocket : public QTcpSocket
{
    Q_OBJECT

public:
    MyTcpSocket(QObject *parent = 0);
    ~MyTcpSocket();

	void ServerWriteData();

signals:
    void sigSocketRecvData(QString, int);
    void sigSocketDisconnect(int);

public slots:
    void OnReadyReadSignal();
    void OnDisconnectedSignal();

private:
	static int m_nIndex;
};

#endif // MYTCPSOCKET_H
// MyTcpSocket.cpp

#include "MyTcpSocket.h"

int MyTcpSocket::m_nIndex = 0;

MyTcpSocket::MyTcpSocket(QObject *parent):
    QTcpSocket(parent)
{
    connect(this, SIGNAL(readyRead()), this, SLOT(OnReadyReadSignal()));		//准备接收
    connect(this, SIGNAL(disconnected()), this, SLOT(OnDisconnectedSignal()));  //断开连接信号

}

MyTcpSocket::~MyTcpSocket()
{

}

void MyTcpSocket::ServerWriteData()
{	
	QString strMsg = QString("World ... %1").arg(m_nIndex++);
	
	//int nSendRet = write(strMsg.toUtf8().data());
	int nSendRet = write(strMsg.toLatin1(), strMsg.length());
	waitForBytesWritten();
	
	if (-1 == nSendRet)
	{
		qDebug() << "Failed to send data " << strMsg;
	}
	else
	{
		qDebug() << "Send data: " << strMsg << endl;
		return;
	}
}

void MyTcpSocket::OnReadyReadSignal()
{
	qDebug() << "On singal ... readyRead";
    while(this->bytesAvailable() > 0) //检查字节数
    {
		char buf[1024] = { 0 };
        int length = bytesAvailable();
        this->read(buf, length); //读取接收
        QString message = QString(QLatin1String(buf)); 

		qDebug() << "socket recv: " << message;
        emit sigSocketRecvData(message, length); //发射信号

		ServerWriteData();
    }

}

void MyTcpSocket::OnDisconnectedSignal()
{
	qDebug() << "On singal ... Disconnected!";

    emit sigSocketDisconnect(this->socketDescriptor());
}

// MyTcpServer.h

#ifndef MYTCPSERVER_H
#define MYTCPSERVER_H

#include "MyTcpSocket.h"
#include <QtNetwork>

class MyTcpServer : public  QTcpServer
{
    Q_OBJECT

public:
    explicit MyTcpServer(QObject *parent = 0);
    ~MyTcpServer();
   
	void MyTcpServerListen();

protected:
    //void incomingConnection(int socketDescriptor);
    void incomingConnection(qintptr socketDescriptor);

signals:
    void sigServerRecvData(QString, int);

public slots:
    void OnSocketRecvDataSignal(QString,int);
    void OnSocketDisconnectSignal(int);

private:
	QList<MyTcpSocket*> tcpSocketList;
	//协议端口号
	int m_nPort;

};

#endif // MYTCPSERVER_H
// MyTcpServer.cpp

#include "MyTcpServer.h"
#include <QtNetwork/QTcpSocket>

MyTcpServer::MyTcpServer(QObject *parent) :
    QTcpServer(parent)
{
	m_nPort = 8010;
}

MyTcpServer::~MyTcpServer()
{
	for (int n = 0; n < tcpSocketList.size(); ++n)
	{
		MyTcpSocket *item = (MyTcpSocket *)tcpSocketList.at(n);
		if (NULL != item)
		{
			qDebug() << "MyTcpServer destruct ... " << n;
			delete item;
			item = NULL;

		}
	}
}

void MyTcpServer::MyTcpServerListen()
{
	this->listen(QHostAddress::Any, m_nPort); //监听本机的 IP 地址和端口
	qDebug() << "Start listening port:" << m_nPort;

	waitForNewConnection(10000);
}

//void MyTcpServer::incomingConnection(int socketDescriptor)
void MyTcpServer::incomingConnection(qintptr socketDescriptor)
{
    qDebug()<< "new client connect ... ";
    MyTcpSocket *tcpSocket = new MyTcpSocket(this);
	QString ip = tcpSocket->peerAddress().toString();
	qint16 port = tcpSocket->peerPort();

	qDebug() << "IP: " << ip << " ... Port: " << (uint16_t)port << endl;

    connect(tcpSocket, SIGNAL(sigSocketRecvData(QString,int)), this, SLOT(OnSocketRecvDataSignal(QString,int)));
    connect(tcpSocket, SIGNAL(sigSocketDisconnect(int)), this, SLOT(OnSocketDisconnectSignal(int)));

    tcpSocket->setSocketDescriptor(socketDescriptor);
    tcpSocketList.append(tcpSocket); //在 list 末尾插入数据

	tcpSocket->waitForDisconnected(8000);

}

void MyTcpServer::OnSocketRecvDataSignal(QString message, int length)
{
	qDebug() << "server recv ..." << message;

    //emit sigServerRecvData(message, length); //发射信号

    //for(int i = 0; i < tcpSocketList.count(); i++)
    //{
    //    QTcpSocket *temp = tcpSocketList.at(i);
    //    if(temp->write(message.toLatin1(), length) != length)
    //    {
    //        continue;
    //    }
    //}
}

void MyTcpServer::OnSocketDisconnectSignal(int descriptor)
{
	qDebug() << "server disconnect ..." ;

    for(int i = 0; i < tcpSocketList.count(); i++)
    {
        QTcpSocket *temp = tcpSocketList.at(i);
        if(temp->socketDescriptor() == descriptor)
        {		
            tcpSocketList.removeAt(i);

			delete temp;
			temp = NULL;
			qDebug() << "temp destruct ..." << i;

            return;
        }
    }
    return;

}
#include <QtCore/QCoreApplication>
#include "MyTcpServer.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
	   
	//实例 tcpServer
	MyTcpServer *tcpServer = new MyTcpServer(nullptr);
	tcpServer->MyTcpServerListen();

	//std::this_thread::sleep_for(std::chrono::seconds(15));

	delete tcpServer;
	tcpServer = NULL;

	qDebug() << "server over ...";

    return a.exec();
}

客户端代码

// MyTcpClient.h

#pragma once

#include <QObject>
#include <QtNetwork>
#include <QTcpSocket>

#pragma execution_character_set("utf-8")

class MyTcpClient  : public QObject
{
	Q_OBJECT

public:
	MyTcpClient(QObject *parent);
	~MyTcpClient();

	void MyTcpConnect();
	void MyTcpDisconnect();

	void MyWriteData();

private slots:		
	void OnDisconnectSignal();
	void OnReadyReadSignal();
	
private:
	QTcpSocket *m_pTcpSocket;

	QString m_strIP;
	int m_nPort;

	int m_nIndex;
};
// MyTcpClient.cpp

#include "MyTcpClient.h"

MyTcpClient::MyTcpClient(QObject *parent)
	: QObject(parent)
{
	m_strIP = "127.0.0.1";
	m_nPort = 8010;

	m_nIndex = 0;
}

MyTcpClient::~MyTcpClient()
{
	if (NULL != m_pTcpSocket)
	{
		qDebug() << "MyTcpClient destruct";
		delete m_pTcpSocket;
		m_pTcpSocket = nullptr;
	}
}

void MyTcpClient::MyTcpConnect()
{
	qDebug() << "client connect ... ";

	m_pTcpSocket = new QTcpSocket(this);
	//connect(m_pTcpSocket, SIGNAL(connected()), this, SLOT(tcpConnected()));
	connect(m_pTcpSocket, SIGNAL(readyRead()), this, SLOT(OnReadyReadSignal()));
	//connect(m_pTcpSocket, SIGNAL(disconnected()), this, SLOT(OnDisconnectSignal()));
	
	m_pTcpSocket->connectToHost(m_strIP, m_nPort);
	m_pTcpSocket->waitForConnected(30000);
		
}

void MyTcpClient::MyTcpDisconnect()
{
	OnDisconnectSignal();
}

void MyTcpClient::MyWriteData()
{
	QString strMsg = QString("Hello ... %1").arg(m_nIndex++);
	char bufferMsg[1024] = { 0 };

	strcpy_s(bufferMsg, strMsg.toStdString().c_str());
	int nSendRet = m_pTcpSocket->write(bufferMsg, strlen(bufferMsg));
	//int nSendRet = m_pTcpSocket->write(strMsg.toUtf8().data());
	m_pTcpSocket->waitForBytesWritten();
	if (-1 != nSendRet)
	{
		qDebug() << "Send data: " << strMsg;		
	}
	else
	{
		qDebug() << "Failed to send data " << strMsg;
	}
	return;
}

void MyTcpClient::OnDisconnectSignal()
{
	qDebug() << "client disconnect ... ";

	m_pTcpSocket->waitForDisconnected(1000);

	//主动和对方断开连接
	m_pTcpSocket->disconnectFromHost();
	m_pTcpSocket->close();//这里释放连接,前面connect的时候会建立连接
}

void MyTcpClient::OnReadyReadSignal()
{
	while (m_pTcpSocket->bytesAvailable() > 0)
	{
		QByteArray datagram;
		datagram.resize(m_pTcpSocket->bytesAvailable());
		m_pTcpSocket->read(datagram.data(), datagram.length());
		//m_pTcpSocket->waitForReadyRead(1000);
		QString message = datagram.data();
		//listWidget->addItem(message);
		qDebug() << "Recv data: "<< message;
	}
}


// main.cpp

#include <QtCore/QCoreApplication>
#include "MyTcpClient.h"

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

	MyTcpClient*  client = new MyTcpClient(nullptr);
	client->MyTcpConnect();

	for (int n = 0; n < 3; n++)
	{
		client->MyWriteData();
		std::this_thread::sleep_for(std::chrono::milliseconds(1000));
	}

	std::this_thread::sleep_for(std::chrono::seconds(1));

	client->MyTcpDisconnect();

	delete client;
	client = NULL;

	qDebug() << "client over ...";

    return a.exec();
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值