QTcpSocket 不通过事件,直接等待获取数据结果

本文介绍了一个使用QTcpSocket进行网络通信的例子,包括连接到指定IP和端口、发送数据并接收响应的过程。该方法适用于需要进行客户端与服务器间简单通信的应用场景。
class SS : public QObject
{
	Q_OBJECT
public:
	static QString getData(QString ip,int port,QString data)
	{
		QTcpSocket *m_pSocket=new QTcpSocket();
		
		m_pSocket->connectToHost(ip, port);
		
		if (!m_pSocket->waitForConnected())
		{
			return "noce";
		}
		//connect(m_pSocket, SIGNAL(connected()), &eventLoop, SLOT(quit()));
		//eventLoop.exec(); 
		if (m_pSocket->isOpen()==true)
		{
			int length = 0;
			
			m_pSocket->write(data.toLatin1(),data.length());
			m_pSocket->waitForBytesWritten(10000);
			QString datastr="";
			while (m_pSocket->waitForReadyRead(60000))
			{
				
				while(m_pSocket->bytesAvailable())
				{       
					QString vTemp;
					vTemp = m_pSocket->readLine();
					datastr.append(vTemp);
				}
				
				
			}
			
			if (datastr!="")
				return datastr;

			
			if (m_pSocket->isOpen()==false)
			{

				m_pSocket->close();
			}
			return "err";
		}else{
			return "noconnect";
		}
		
	}

};

 

转载于:https://my.oschina.net/xavier007/blog/690211

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值