QT编程系列11--Qt网络编程的补充(一)

QT编程系列11--Qt网络编程的补充(一)

 

    在QT编程系列10一文中,介绍了客户端在接收来自服务器端的数据前,首先会有一个信号被触发即readyRead()。那么该函数触发后会有一个槽函数来实现处理这个事件。那么处理这个事件的函数我们定义成了myread()函数。在上文中我们使用的代码是:

  1. void mywindow::myread(void){  
  2.     QString tmp;  
  3.     int i;  
  4.     QTime tt;  
  5.     tt = QTime::currentTime ();  
  6.     QString time_str;  
  7.     time_str = tt.toString("hh:mm:ss");  
  8.     UART_Format uformat;      
  9.     tcpsocket->read((char *)&uformat,(quint64)sizeof(uformat));    
  10.     tmp.append(time_str);  
  11.   
  12.     tmp.append(" ");  
  13.     tmp.append(QString::number (uformat.Header_1,16));      //cc                ee  
  14.     tmp.append(" ");  
  15.     tmp.append(QString::number (uformat.Header_2,16));      //ee                cc  
  16.     tmp.append(" ");  
  17.     tmp.append(QString::number (uformat.NodeSeq,16)); //模块序列 01             01  
  18.     tmp.append(" ");  
  19.     tmp.append(QString::number (uformat.NodeID,16)); //模块ID (00表示网关)    DeviceAddrList  Motor == 9   
  20.     tmp.append(" ");  
  21.     tmp.append(QString::number (uformat.Command,16));           //功能 01         dd  
  22.     tmp.append(" ");  
  23.     for(i = 0; i < 10; i++){  
  24.     tmp.append(QString::number (uformat.Data[i],16));       //无用                保存节点的数据  
  25.     tmp.append(" ");  
  26.     }  
  27.     tmp.append(QString::number (uformat.Tailer,16));            //ff  
  28.     tmp.append(" ");  
  29.   
  30.   
  31.     tedit->append(tmp);  
  32. }

    这段代码8、9两行是在接收串口中的数据,而在在QT编程系列9中,服务器端一直在每隔1000ms发送一次"hello world"这11个字符。那么我们该如何接收来自服务器端发送的网络数据,而不是串口数据了?这里给出两种方法。先贴出代码:

/************************************************
				myread()的第一种实现方法
************************************************/
void mywindow::myread(void)
{
	QString tmp;
	//QString readtmp;
	QByteArray vTemp;
	/*QTime tt;
	QString time_str;
	
	tt = QTime::currentTime();
	time_str = tt.toString("hh:mm:ss");
	tmp.append(time_str);*/

	//tcpsocket->read((char *)&readtmp,11);
	vTemp = tcpsocket->readLine();
	//tmp.append(" : ");
	tmp.append(vTemp);

	tedit->append(tmp);

}

/************************************************
				myread()的第二种实现方法
************************************************/
/*void mywindow::myread(void)
{
	while(tcpsocket->bytesAvailable()>0)
	{
		int length = tcpsocket->bytesAvailable();
		char buf[1024];
		tcpsocket->read(buf,length);
		
		QString msg = buf;
		tedit->append(msg);	
	}
}*/



    以上这两种方法实现的功能或者说效果是一样的。试比较一下两种方法的区别主要在于一种方法使用的函数是tcpsocket->readLine(),而另一种方法使用的函数是tcpsocket->read()。这两个函数都是QIODevice类中的方法,一个是返回当前行的内容,一个是返回length长度的内容到buf中。tcpsocket->readLine()函数读取到的值可以直接在edit中显示,而tcpsocket->read()函数读到的值还需要进行转化,如代码中的QString msg = buf语句。在assistant中这两个函数的说明如下:

qint64 QIODevice::readLine ( char * data, qint64 maxSize )

This function reads a line of ASCII characters from the device, up to a maximum of maxSize - 1 bytes, stores the characters in data, and returns the number of bytes read. If a line could not be read but no error ocurred, this function returns 0. If an error occurs, this function returns what it could the length of what could be read, or -1 if nothing was read.

A terminating '\0' byte is always appended to data, so maxSize must be larger than 1.

Data is read until either of the following conditions are met:

The first '\n' character is read.
maxSize - 1 bytes are read.
The end of the device data is detected.
For example, the following code reads a line of characters from a file:

 QFile file("box.txt");
 if (file.open(QFile::ReadOnly)) {
     char buf[1024];
     qint64 lineLength = file.readLine(buf, sizeof(buf));
     if (lineLength != -1) {
         // the line is available in buf
     }
 }
The newline character ('\n') is included in the buffer. If a newline is not encountered before maxSize - 1 bytes are read, a newline will not be inserted into the buffer. On windows newline characters are replaced with '\n'.

This function calls readLineData(), which is implemented using repeated calls to getChar(). You can provide a more efficient implementation by reimplementing readLineData() in your own subclass.

See also getChar(), read(), and write().

 

QByteArray QIODevice::readLine ( qint64 maxSize = 0 )

This is an overloaded member function, provided for convenience.

Reads a line from the device, but no more than maxSize characters, and returns the result as a QByteArray.

This function has no way of reporting errors; returning an empty QByteArray() can mean either that no data was currently available for reading, or that an error occurred.

 

qint64 QIODevice::read ( char * data, qint64 maxSize )

Reads at most maxSize bytes from the device into data, and returns the number of bytes read. If an error occurs, such as when attempting to read from a device opened in WriteOnly mode, this function returns -1.

0 is returned when no more data is available for reading. However, reading past the end of the stream is considered an error, so this function returns -1 in those cases (that is, reading on a closed socket or after a process has died).

See also readData(), readLine(), and write().

 

QByteArray QIODevice::read ( qint64 maxSize )

This is an overloaded member function, provided for convenience.

Reads at most maxSize bytes from the device, and returns the data read as a QByteArray.

This function has no way of reporting errors; returning an empty QByteArray() can mean either that no data was currently available for reading, or that an error occurred.

 

    另外我们还用到了tcpsocket->bytesAvailable()函数,那么该函数是返回可读内容的长度。正好可以配合tcpsocket->read()函数使用。

qint64 QIODevice::bytesAvailable () const   [virtual]

Returns the number of bytes that are available for reading. This function is commonly used with sequential devices to determine the number of bytes to allocate in a buffer before reading.

Subclasses that reimplement this function must call the base implementation in order to include the size of QIODevices' buffer. Example:

 qint64 CustomDevice::bytesAvailable() const
 {
     return buffer.size() + QIODevice::bytesAvailable();
 }

 

By:霜月孤鸟

2015.1.21

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值