基于Qt最简单的客户端服务器数据收发

//服务器实例
class LittleServer :
	public QMainWindow
{
	Q_OBJECT
public:
	LittleServer(void);
	virtual ~LittleServer(void);

public: 
 QUdpSocket *UdpSender;//udp套接字器
QTcpSocket *TcpReciever;//tcp套接字器
QTcpServer* m_TcpServer;//tcp服务器
	QWidget* m_CentralWidget;//中心窗体
	QByteArray datagram;//数据 
	QLabel* m_Label;
	QLineEdit* m_LineEdit;
	QPushButton* m_SendButton;
	public slots:
		void slot_Send();
		void acceptConnection();
        public:	
		void readClient();
	
};

//cpp实现
LittleServer::LittleServer(void)
{
	m_TcpServer=new QTcpServer(this);//创建服务器实例
	TcpReciever=nullptr;//赞无接收套接字
	m_TcpServer->listen(QHostAddress::Any, 8888);//监听端口号为8888,这里自行设计
	connect(m_TcpServer, SIGNAL(newConnection()), this, SLOT(acceptConnection()));//当服务器发现有新的连接时,出发接受新连接函数
	m_Label=new QLabel("",this);
	m_CentralWidget=new QWidget(this);
	QHBoxLayout* mainLayout=new QHBoxLayout(this);
	m_SendButton=new QPushButton("发送",this);
	m_LineEdit=new QLineEdit(this);
	mainLayout->addStretch();
	mainLayout->addWidget(m_SendButton);
        mainLayout->addWidget(m_LineEdit);
	mainLayout->addStretch();
	mainLayout->addWidget(m_Label);
	this->setCentralWidget(m_CentralWidget);
	m_CentralWidget->setLayout(mainLayout);
	UdpSender = new QUdpSocket(this);//暂时没使用
        connect(m_SendButton,SIGNAL(clicked()),this,SLOT(slot_Send()));

}


LittleServer::~LittleServer(void)
{
}
//当点击的时候发送
void LittleServer::slot_Send()
{
	datagram=m_LineEdit->text().toAscii();//得到显示的数据
	//UDP广播
	UdpSender->writeDatagram(datagram.data(),datagram.size(),QHostAddress::Broadcast,6665);

	//向特定IP发送
 	QHostAddress serverAddress = QHostAddress("192.168.20.156");
	int Ret=UdpSender->writeDatagram(datagram.data(), datagram.size(),QHostAddress::LocalHost, 6665);

	/* writeDatagram函数原型,发送成功返回字节数,否则-1
	qint64 writeDatagram(const char *data,qint64 size,const QHostAddress &address,quint16 port)
	qint64 writeDatagram(const QByteArray &datagram,const QHostAddress &host,quint16 port)
	*/

}

void LittleServer::acceptConnection()
{
	//当有客户端连接到服务器的时候:就得到当前的socket,然后有数据就读取
	//qDebug(State:%d\n”,mSocket->state()); // State: 2; 2代表ConnectingState,正确的应该为3(ConnectedState)
	TcpReciever =m_TcpServer->nextPendingConnection();//套接字器指向该链接
	
	
	connect(TcpReciever, SIGNAL(readyRead()), this, SLOT(readClient()));//当有数据来时,触发读取客户端的信息
	QString ipCli =TcpReciever->peerAddress().toString();//链接地址   
	qint16 portCli = TcpReciever->peerPort();//链接方端口
	QString temp = QString("客户端:[%1:%2]:连接成功").arg(ipCli).arg(portCli);
	ipCli=TcpReciever->localAddress().toString();
	portCli=TcpReciever->localPort();
	temp += QString("服务器:[%1:%2]").arg(ipCli).arg(portCli);
	m_Label->setText(temp);//显示服务器客户端分别地址和ip
}

void LittleServer::readClient()
{
//将读取的客户端信息显出来
	TcpReciever->waitForReadyRead();
	QString str = TcpReciever->readAll();

	m_Label->setText(str);
	//或者
	//char buf[1024];
	//m_TcpServer->read(buf,1024);
}
class LittleClient :
	public QMainWindow
{
	Q_OBJECT
public:
	LittleClient(void);
	virtual ~LittleClient(void);
	QTcpSocket* m_TcpSocket;
	QUdpSocket *UdpReceiver;//udp
	QWidget* m_CentralWidget;//中心窗体
	QByteArray datagram;//接受到的数据
	QLabel* m_Label;
	QPushButton* m_ShowButton;

	//信号槽
	private slots:  
		void readPendingDatagrams();
		void sendTcp();
		void ConnectToServerSuccessed();

};
LittleClient::LittleClient(void)
	:UdpReceiver(new QUdpSocket(this))
{

	UdpReceiver->bind(QHostAddress::LocalHost, 6665);//绑定端口
	connect(UdpReceiver, SIGNAL(readyRead()),this, SLOT(readPendingDatagrams()));
	m_CentralWidget=new QWidget(this);
	QHBoxLayout* mainLayout=new QHBoxLayout(this);
	m_ShowButton=new QPushButton("显示",this);
	m_Label=new QLabel("开始",this);

	mainLayout->addStretch();
	mainLayout->addWidget(m_ShowButton);
	mainLayout->addWidget(m_Label);
	mainLayout->addStretch();
	this->setCentralWidget(m_CentralWidget);
	m_CentralWidget->setLayout(mainLayout);
	


	m_TcpSocket=new QTcpSocket(this);
	//m_TcpSocket->abort();
	connect(m_TcpSocket,SIGNAL(connected()),this,SLOT(ConnectToServerSuccessed()));
	m_TcpSocket->connectToHost(QHostAddress::LocalHost,8888);//链接服务器
	bool isConnected=m_TcpSocket->waitForConnected();//只有使用waitForConnected()后,QTcpSocket才真正尝试连接服务器,并返回是否连接的结果。
	//m_TcpSocket->connectToHost("192.168.20.156", 9999);//先建立链接
	connect(m_ShowButton,SIGNAL(clicked()),this,SLOT(sendTcp()));
	
}


LittleClient::~LittleClient(void)
{
}

void LittleClient::readPendingDatagrams()
{
   	while (UdpReceiver->hasPendingDatagrams()) {
		datagram.resize(UdpReceiver->pendingDatagramSize());
		UdpReceiver->readDatagram(datagram.data(), datagram.size());
		m_Label->setText(QString(datagram));
		//数据接收在datagram里
		/* readDatagram 函数原型
		qint64 readDatagram(char *data,qint64 maxSize,QHostAddress *address=0,quint16 *port=0)
		*/
	}
}

void LittleClient::sendTcp()
{
	QString str=m_Label->text();
	//m_TcpSocket->write(str.toAscii());
	
	m_TcpSocket->write("12345",5);
	//m_TcpSocket->write(str.toStdString().c_str(), strlen(str.toStdString().c_str()));
	bool isSend=m_TcpSocket->waitForBytesWritten(); //当使用waitForBytesWritten()后,QTcpSocket才真正发送数据。 
}

void LittleClient::ConnectToServerSuccessed()
{
	
	m_Label->setText(QString("服务器:[%1:%2 客户端:%3:%4]").arg(m_TcpSocket->peerAddress().toString()).arg(m_TcpSocket->peerPort()).arg(m_TcpSocket->localAddress().toString()).arg(m_TcpSocket->localPort()));

}

然后分别创建该littleclient实例和 littleserver实例,即可进行通讯(端口和Ip依据实际情况填写),其中tcp收发信息需要客户端和服务端先建立链接,才行,而udp发送消息则不需要理会,只管发,不管对方是否接受或者处理。

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 在Qt,可以使用QUdpSocket类来实现UDP客户端接收服务器数据。首先创建一个QUdpSocket对象: QUdpSocket *udpSocket = new QUdpSocket(this); 然后使用bind()函数将该udpSocket绑定到一个本地端口: udpSocket->bind(localPort); 其localPort是一个本地端口号,用于接收服务器端发送的数据。 接下来,可以使用readyRead()信号和QByteArray类来接收数据。readyRead()信号在有数据到达时触发,我们可以使用信号槽机制连接它: connect(udpSocket, SIGNAL(readyRead()), this, SLOT(processPendingDatagrams())); 接收数据的具体实现可以在processPendingDatagrams()槽函数完成: void MyClass::processPendingDatagrams() { while (udpSocket->hasPendingDatagrams()) { QByteArray datagram; datagram.resize(udpSocket->pendingDatagramSize()); udpSocket->readDatagram(datagram.data(), datagram.size()); // 处理接收到的数据 } } 在该槽函数,我们利用hasPendingDatagrams()函数判断是否有待处理的数据包,如果有,就使用readDatagram()函数读取数据包的内容。 最后,可以在处理接收到的数据的部分添加逻辑来完成对接收到的数据的处理。 以上就是在Qt实现UDP客户端接收服务器数据的方法。 ### 回答2: QT是一种开发工具,UDP是一种网络通信协议,客户端指的是对UDP服务器进行请求并接收数据的一方,服务器端是负责接收请求并提供数据的一方。 在QT,开发客户端来接收UDP服务器端的数据可以按照以下步骤进行: 1. 创建一个QT项目,并在项目添加UDP相关的头文件和库文件。 2. 使用QT提供的QUdpSocket类来创建一个UDP套接字对象。套接字对象是用来进行网络通信的对象。 3. 配置套接字对象的相关参数,如绑定端口号。 4. 使用套接字对象的bind()函数将套接字绑定到特定的主机和端口号上。 5. 使用套接字对象的readyRead()信号和对应的槽函数来接收服务器端的数据。 6. 在槽函数调用套接字对象的readDatagram()函数来读取接收到的数据,并进行处理。 7. 根据具体需求,可以在接收到数据后对数据进行解析、展示或者其他操作。 8. 可以使用套接字对象的writeDatagram()函数向服务器端发送数据。 9. 在必要的情况下,可以在客户端服务器端的通信过程使用一些错误处理机制,如超时重发等。 通过以上步骤,就可以在QT实现UDP客户端接收服务器端的数据。接收到的数据可以根据需求进行处理和展示,以满足具体的业务需求。 ### 回答3: Qt是一个跨平台的C++应用程序开发框架,支持多种网络通信协议,其包括UDP协议。 在Qt,可以通过QUdpSocket类来实现UDP客户端。首先,需要创建一个QUdpSocket对象,并通过bind函数绑定本地地址和端口号。然后,可以使用receiveDatagram函数来接收服务器端发送过来的数据。 接收数据的代码示例: ```cpp QUdpSocket *udpSocket = new QUdpSocket(this); udpSocket->bind(QHostAddress::AnyIPv4, 1234); // 绑定本地地址和端口号 QByteArray datagram; // 用于存储接收到的数据 datagram.resize(udpSocket->pendingDatagramSize()); QHostAddress senderAddress; // 存储数据发送者的地址 quint16 senderPort = 0; // 存储数据发送者的端口号 udpSocket->readDatagram(datagram.data(), datagram.size(), &senderAddress, &senderPort); // 使用datagram数据进行后续处理 delete udpSocket; ``` 在以上代码,通过udpSocket->bind函数指定了本地地址AnyIPv4和端口号1234,表示接收来自任意地址的UDP数据包。通过udpSocket->readDatagram函数接收数据,并将数据存储在datagram,同时获取发送者的地址和端口号。 需要注意的是,接收数据的操作是阻塞的,即在调用udpSocket->readDatagram函数时,如果没有接收到数据,程序将一直等待,直到接收到数据或发生错误。 总之,通过以上代码,我们可以在Qt实现UDP客户端接收服务器端发送的数据
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值