Данные не передаются между QTcpSockets и Java Sockets - PullRequest
0 голосов
/ 23 марта 2019

Итак, у меня есть два приложения, одно написано на C ++ с использованием Qt5, а другое написано на Java.Приложение C ++ действует как клиент, который подключается к объекту ServerSocket в приложении java, которое затем создает сокет из соединения.Затем, когда я пытаюсь отправить строку на сервер, я должен либо отправить строку повторно (например, 20000 раз), либо сервер вообще ничего не получает.

QString s = " This is a test string that will be sent to the server upon connection\n";
QTcpSocket *sock = new QTcpSocket;
sock->connectToHost(QHostAddress::LocalHost, 5000, QIODevice::ReadWrite);
sock->waitForConnected(5000);
QTextStream out(sock);
while(!sock->waitForBytesWritten(3000)) {
        out << s << endl;
}

Если приведенный выше код не даст никаких результатов, следующие строки дают сегментированные строки, а также дубликаты полученных строк для сервера:

QString s = " This is a test string that will be sent to the server upon connection\n";
QTcpSocket *sock = new QTcpSocket;
sock->connectToHost(QHostAddress::LocalHost, 5000, QIODevice::ReadWrite);
sock->waitForConnected(5000);
QTextStream out(sock);
do {
        out << s << endl;
} while(!sock->waitForBytesWritten(3000) | 1);

Сервер представляет собой простую Java-программувот так:

ServerSocket ss = new ServerSocket(5000);
Socket s = ss.accept();
DataInputStream in = new DataInputStream(s.getInputStream());
while (true){
        String tmp = in.readUTF();
        System.out.println(tmp);
        if (tmp.contains(" ")){
              break;
}

Я ожидаю, что результат будет простым This is a test string that will be sent to the server upon connection;однако в результате получается либо ничего, либо что-то в этом роде:

his is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

 This is a test string that will be sent to the server upon connection

Есть ли у вас какие-либо идеи относительно того, как я могу решить эту проблему?

Ответы [ 2 ]

0 голосов
/ 24 марта 2019

(1) waitForBytesWritten может не работать в Windows - лучше использовать сигнал bytesWritten()

(2) Петля

while(!sock->waitForBytesWritten(3000) | 1);

выглядит для меня как бесконечный цикл, независимо от кода возврата от waitForBytesWritten

(3) Какова идея waitForBytesWritten в контексте вашей программы? Может возвращаться после первого байта, записанного в поток!

(4) В чем идея

if (tmp.contains(" ")){
              break;

Мне кажется, это может сломаться после любого полученного бланка - например, первый пробел после «Это». Это может также сломаться после нескольких строк, в зависимости от того, сколько доставляет readUTF (я не эксперт по Java).

(5) readUTF ожидает строки в модифицированном формате UTF8, но Qt не будет отправлять строки в модифицированном UTF8 (с ведущим 16-битным целым числом, содержащим длину). Таким образом, Java будет интерпретировать первые два символа ('Th') как длину, и тогда лотерея может начаться - в зависимости от этих двух символов, декодирование выдаст, казалось бы, произвольные результаты.

0 голосов
/ 24 марта 2019

Таким образом, решение состояло в том, чтобы прочитать данные в byte[] и затем преобразовать, используя строковый конструктор, в строку как таковую:

ServerSocket ss = new ServerSocket(5000);

Socket s = ss.accept();

DataInputStream in = new DataInputStream(s.getInputStream());

byte[] b = new byte[1024];
in.read(b);

String tmp = new String(b, "UTF8");
System.out.println(b);
System.out.println(tmp);

Понятия не имею почему, но это решение, к которому я пришел. Клиент практически не изменился, хотя были внесены незначительные изменения:

QString s = "This is a test string that will be sent to the server upon connection\n";

QTcpSocket *sock = new QTcpSocket;

sock->connectToHost(QHostAddress::LocalHost, 5000, QIODevice::ReadWrite);

sock->waitForConnected(5000);


do {
        sock->write(s.toUtf8());
        sock->flush();

        sock->waitForBytesWritten();
} while (sock->isValid() && sock->bytesToWrite() > 0);
...