Qt version:5.2
download了一份4.8的代码下来研究这个tcp通信。
结果挺萌的,QTextCodec中各种方法过时和被抛弃;
编译都通不过。
将有关编码的代码全部删除后,通过了 并且能够运行。但是。。
挺萌的,乱码。发送和接受都乱码。
研究找到解决方法如下。
参考两段代码,发送和接受的:
发送:
1 2 3 4 5 |
void TcpS::btn_send() { QByteArray datasend = ui->textEdit->toPlainText().toLocal8Bit(); m_tcpsocket->write(datasend); } |
接收:
1 2 3 4 5 6 |
void TcpS::read_datagram() { QByteArray dataread = m_tcpsocket->readAll(); QString str = QString::fromLocal8Bit(dataread); ui->textBrowser->insertPlainText(str+"\n"); } |
用到的就是fromLocal8Bit 和 toLocal8Bit方法;
关于fromLocal8Bit ,官方文档:
1 2 3 4 5 6 |
QString QString::fromLocal8Bit(const QByteArray & str) [static] This is an overloaded function. Returns a QString initialized with the 8-bit string str. This function was introduced in Qt 5.0. |
关于toLocal8Bit,官方文档:
1 2 3 4 5 6 7 8 |
QByteArray QString::toLocal8Bit() const Returns the local 8-bit representation of the string as a QByteArray. The returned byte array is undefined if the string contains characters not supported by the local 8-bit encoding. QTextCodec::codecForLocale() is used to perform the conversion from Unicode. If the locale encoding could not be determined, this function does the same as toLatin1(). If this string contains any characters that cannot be encoded in the locale, the returned byte array is undefined. Those characters may be suppressed or replaced by another. See also fromLocal8Bit(), toLatin1(), toUtf8(), and QTextCodec. |
第一次访问,支持一下哈。
[…] 也可以看看这个。 […]