S
S
Sencis2019-02-01 10:02:58
Computer networks
Sencis, 2019-02-01 10:02:58

Writing data to Tcp socket from another thread?

On a unicameral computer, 2a threads work. First, the TCP server sends data from the target PC to the UART. The second checks the buffer for data (polling). UART is very slow, so it's impossible to start everything in one thread. It is necessary to send data to the UART via Tcp Server to the target PC upon arrival of data to the UART, but when calling the write method to the port, the server falls on the write ( socket-> write ( data ); ) or even so it does not allow writing to the port ( socket-> write ( "data" ); ). Where can I find documentation or an example to solve this problem?
The UART protocol error occurs after the parser calls the write method myserver.write();

void UART_Protokol::ParseCommand()
{
   MyServer myserver;

  if(sp_dataString == "Start") { TransmitData = "ready"; sp_Send(TransmitData); qDebug()<<"Самопроверка"; }
  if(sp_dataString == "ready") qDebug()<<"Самопроверка";

  if (sp_dataString =="MG1")  myserver.write("MG1");   //Например здесь
  if (sp_dataString =="MG0")  myserver.write("MG0");
  if (sp_dataString =="MG")  qDebug()<<"Калибровка...";
}

Part of the Tcp server here is the write method MyServer::write at the very end:
#include "myserver.h"


MyServer::MyServer(){} //коструктор

MyServer::~MyServer(){}//деструктор




void MyServer::startserver()

{
    if (this->listen(QHostAddress::Any,8981))qDebug()<<"Сервер запущен";
    else{ qDebug()<<"Ошибка при попытки старта сервера";}

}



void MyServer::incomingConnection(int socketDescriptor ) // обработчик подключений название метода обязательно должно быть incomingConnection
{
    socket = new QTcpSocket(this);

    socket->setSocketDescriptor( socketDescriptor);// присовение уникального номера порта

    connect(socket,SIGNAL(readyRead()),this,SLOT(read())); // соединение прерывания порта с методом чтения

    connect(socket,SIGNAL(disconnected()),this,SLOT(disconect())); //соединение прерывания разрыва соединнинения с методом

    qDebug()<<socketDescriptor<<":Клиент подключен";

    socket->write("Connection");

}
void MyServer::read()
{
     UART_Protokol UART;

     UART.StartProtokol( false );

     arr = socket->readAll();
     data += arr;


      if ( data == "wu" )UART.sp_Send("wu");
      if ( data == "su" )UART.sp_Send("su");
      if ( data == "au" )UART.sp_Send("au");
      if ( data == "du" )UART.sp_Send("du");
      if ( data == "qu" )UART.sp_Send("qu");
      if ( data == "eu" )UART.sp_Send("eu");
      if ( data == "wd" )UART.sp_Send("wd");
      if ( data == "sd" )UART.sp_Send("sd");
      if ( data == "ad" )UART.sp_Send("ad");
      if ( data == "dd" )UART.sp_Send("dd");
      if ( data == "qd" )UART.sp_Send("qd");
      if ( data == "ed" )UART.sp_Send("ed");
      if (data == "SD1")UART.sp_Send("SD1");
      if (data == "SD0")UART.sp_Send("SD0");
      if (data == "cl")UART.sp_Send("cl");

      if( arr[0] == Mask[0]&& arr[1] == Mask[1])
      {
          int length = 0;

          QByteArray dt = "tr";

          trust[0] =0;
          trust[1] =0;
          trust[2] =0;

          length = arr[2];
          trust[0] =arr[3];
          trust[1] =arr[4];
          trust[2] =arr[5];

          truster = convert(trust, length - 48);

          dt[2] = truster;

          UART.sp_Send_integer(dt);
      }

      arr.clear(); //На случай если ошибка длинны появляется из-за неправильной очистки массива.
      data = "";

}

void MyServer::disconect()

{ 
    socket->deleteLater();
}


void MyServer::write (QByteArray dat)
{
  
 //Здесь происходит ошибка

 qDebug()<<dat;  // Дебаг всё выводит

 socket->write(dat);

// Так тоже не работает  socket->write ("MG1");

}

Starting threads:
#include <QCoreApplication>
#include <myserver.h>
#include <protokol_obmena_cherez_uart.h>
#include <QDebug>
#include <thread>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);


    UART_Protokol Serial;

    Serial.StartProtokol( false );

    std::thread serial (&UART_Protokol::Event, Serial);  


    MyServer Server;

    Server.startserver();


    return a.exec();
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2019-02-01
@Userpc0101

Pass data to the server thread in some way (queue, messages, etc.) and let the server send it itself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question